package com.yuanfeng.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.config.PermissionsConstant;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.base.DealerGoodsUserInfoDTO;
import com.yuanfeng.commoms.dto.goods.*;
import com.yuanfeng.commoms.dto.oos.OssUploadUpdateParamDTO;
import com.yuanfeng.commoms.dto.shop.ShopEvaluationDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.rocketmq.MqSendUtils;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.excel.ExcelsUtil;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.util.secverifyapiutil.Base64Utils;
import com.yuanfeng.commoms.vo.activity.*;
import com.yuanfeng.commoms.vo.base.BaseGoodsConfigVO;
import com.yuanfeng.commoms.vo.goods.*;
import com.yuanfeng.commoms.vo.shop.GdsShopDetailResultVO;
import com.yuanfeng.commoms.vo.shop.InvoiceSwitchEntityVO;
import com.yuanfeng.commoms.vo.shop.ManageShopSelfCatMenuVO;
import com.yuanfeng.commoms.vo.shop.TransportTemplateVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.goods.dto.*;
import com.yuanfeng.goods.entity.GoodsBaseEntity;
import com.yuanfeng.goods.entity.GoodsCommonEntity;
import com.yuanfeng.goods.feign.ActivityServiceClient;
import com.yuanfeng.goods.feign.BaseServiceClient;
import com.yuanfeng.goods.feign.BusinessServiceClient;
import com.yuanfeng.goods.feign.ThirdPartyServiceClient;
import com.yuanfeng.goods.mapper.*;
import com.yuanfeng.goods.service.GoodsBaseService;
import com.yuanfeng.goods.service.GoodsCommonService;
import com.yuanfeng.goods.util.es.AccessTokenUtil;
import com.yuanfeng.goods.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @ClassName GoodsBaseServiceImpl
 * @Description 商品表
 * @Author cyp
 * @Date 2023-05-25 09:16:35
 * @Version 1.0
 **/
@Service
public class GoodsBaseServiceImpl extends ServiceImpl<GoodsBaseMapper, GoodsBaseEntity>
        implements GoodsBaseService {

    private final static Logger LOG = LoggerFactory.getLogger(GoodsBaseServiceImpl.class);

    @Autowired
    private ActivityServiceClient activityServiceClient;
    @Autowired
    private BusinessServiceClient businessServiceClient;
    @Autowired
    private BaseServiceClient baseServiceClient;
    @Resource
    private ShopBaseMapper shopBaseMapper;
    @Resource
    private GoodsCommonMapper goodsCommonMapper;
    @Resource
    private GoodsCommonAttributeAssociationMapper goodsCommonAttributeAssociationMapper;
    @Resource
    private BaseSysConfigsMapper baseSysConfigsMapper;
    @Resource
    private GoodsImagesMapper goodsImagesMapper;
    @Resource
    private GoodsHotMapper goodsHotMapper;
    @Resource
    private GoodsPropertyIndexMapper goodsPropertyIndexMapper;
    @Resource
    private GoodsCommonDetailMapper goodsCommonDetailMapper;
    @Resource
    private GoodsDelayConfigMapper goodsDelayConfigMapper;
    @Resource
    private ShopGoodsCatMapper shopGoodsCatMapper;
    @Resource
    private ShopSelfCatMapper shopSelfCatMapper;
    @Resource
    private ThirdPartyServiceClient thirdPartyServiceClient;
    @Resource
    private GoodsSpecValueMapper goodsSpecValueMapper;
    @Resource
    private GoodsAttributeMapper goodsAttributeMapper;
    @Resource
    private GoodsAttributeContentMapper goodsAttributeContentMapper;
    @Resource
    private ShopTransportTemplateMapper shopTransportTemplateMapper;
    @Resource
    private ShopTransportAreaMapper shopTransportAreaMapper;
    @Resource
    private GoodsSpecMapper goodsSpecMapper;
    @Resource
    private GoodsHotMapper getGoodsHotMapper;
    @Resource
    private GoodsPropertyMapper goodsPropertyMapper;
    @Autowired
    private GoodsCommonService goodsCommonService;
    @Autowired
    private GoodsCommonServiceImpl goodsCommonServiceImpl;

    @Value("${system.pcIndexConfig}")
    private  String pcIndexConfig ;

    @Value("${domainName}")
    public String domainName;

    static String[] suffix ={".text",".pdf",".word",".png",".jpg",".jpeg"};
    @Override
    public ResponseResult updateGoodsCollect(Integer goodId) {
        GoodsBaseEntity goodsBaseEntityentit = this.baseMapper.selectById(goodId);
        if(goodsBaseEntityentit.getGoodsCollect()>0){
            this.baseMapper.update(goodsBaseEntityentit, new LambdaUpdateWrapper<GoodsBaseEntity>().eq(GoodsBaseEntity::getGoodsId, goodId)
                    .set(GoodsBaseEntity::getGoodsCollect, goodsBaseEntityentit.getGoodsCollect() - 1));
        }


        return ResponseResult.success();
    }

    @Override
    public ResponseResult getGoodsDetails(Integer goodsId) {
        ReceiveGoodsDetailsDTO detail = this.baseMapper.selectCartMessage(goodsId);
        if (null == detail) {
            return ResponseResult.fail(BizCodeEnume.PRODUCT_HAS_BEEN_REMOVED_FROM_THE_SHELF);
        }

        if (!detail.getCommonState().equals(1) || !detail.getCommonVerify().equals(1)
                || (detail.getCartStatus() != null && !detail.getCartStatus().equals(0))) {
            detail.setGoodsStock(0);
            detail.setCartStatus(0);
        }

        // 不限购
        if (detail.getCommonLimit().equals(0) || detail.getGoodsMaxSale().equals(0)) {
            detail.setGoodsMaxSale(0);
        }

        // 活动
        Integer integer = dealActivityState(detail.getGoodsId(), detail.getGoodsMaxSale(),
                detail.getCommonId(), detail.getCommonIsXian());
        if (integer != null && integer == -100){
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),"该商品存在问题");
        }
        detail.setActivityGoodsState(integer);
        ActivityGoodsDetailDTO activityGoodsDetail = dealActivity(detail.getGoodsId(), detail.getGoodsMaxSale(),
                detail.getCommonId(), detail.getCommonIsXian());

        if (null != activityGoodsDetail && !activityGoodsDetail.getActivityStatus().equals(0)) {
            detail.setActivityStatus(activityGoodsDetail.getActivityStatus());
            detail.setActivityGoodsDetail(activityGoodsDetail);
            detail.setCommonIsXian(activityGoodsDetail.getActivityStatus());
            detail.setGoodsStartTime(activityGoodsDetail.getActivityStartTime());
            if (!activityGoodsDetail.getActivityStatus().equals(4) && (activityGoodsDetail.getActivityStartTime() != null
                    && activityGoodsDetail.getActivityStatus() == 2 && !DateUtils.compareDate2(activityGoodsDetail.getActivityStartTime()))) {
                detail.setGoodsMaxSale(activityGoodsDetail.getGoodsUpperLimit());
                detail.setGoodsMinSale(activityGoodsDetail.getGoodsLowerLimit());

                //若为限时折扣活动
                if(activityGoodsDetail.getActivityStatus().equals(3)){

                }
            }
        } else {
            detail.setActivityStatus(0);
            detail.setActivityGoodsDetail(new ActivityGoodsDetailDTO());
            detail.setCommonIsXian(0);
        }

        if (detail.getGoodsMaxSale().equals(0)) {
            detail.setGoodsMaxSale(0);
        }

        return ResponseResult.success(JsonUtils.toString(detail));
    }

    private Integer dealActivityState(Integer goodsId, Integer goodsMaxSale, Integer commonId,
                                      Integer commonIsXian) {
        // 活动商品详情
        ActivityGoodsDetailDTO activityGoodsDetail = null;
        Integer activityGoodsState = null;
        // 商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣,4拼团,5满减赠折
        if (!commonIsXian.equals(0)) {
            activityGoodsDetail = new ActivityGoodsDetailDTO();
            if (commonIsXian.equals(2)) {
                // 秒杀
                AppSeckillGoodsQueryResultVO seckillGoods = activityServiceClient.selectSeckillByGoodsId2(goodsId);
                if (seckillGoods != null){
                    activityGoodsState = seckillGoods.getSeckillGoodsState();
                }
            } else if (commonIsXian.equals(3)) {
                // 限时折扣
                AppDiscountGoodsQueryResultVO discountGoods = activityServiceClient.selectDiscountByGoodsIdAndTime(goodsId);
                if (discountGoods != null){
                    activityGoodsState = discountGoods.getDiscountGoodsState();
                }
            }
            activityGoodsDetail.setActivityStatus(commonIsXian);
        }

        return activityGoodsState;
    }

    private ActivityGoodsDetailDTO dealActivity(Integer goodsId, Integer goodsMaxSale, Integer commonId,
                                             Integer commonIsXian) {
        // 活动商品详情
        ActivityGoodsDetailDTO activityGoodsDetail = null;
        // 商品是否参加促销0不参加,1砍价,2秒杀,3限时折扣,4拼团,5满减赠折
        if (!commonIsXian.equals(0)) {
            activityGoodsDetail = new ActivityGoodsDetailDTO();
            if (commonIsXian.equals(2)) {
                // 秒杀
                AppSeckillGoodsQueryResultVO seckillGoods = activityServiceClient.selectSeckillByGoodsId2(goodsId);
                commonIsXian = goodsCommonServiceImpl.dealSeckillActivity1(commonId, goodsId, goodsMaxSale, commonIsXian, activityGoodsDetail, null);
                if(seckillGoods != null) {
                    activityGoodsDetail.setSeckillGoods(seckillGoods);
                    activityGoodsDetail.setGoodsUpperLimit(seckillGoods.getGoodsUpperLimit());
                    activityGoodsDetail.setActivityStartTime(seckillGoods.getGoodsStartTime());
                }
            } else if (commonIsXian.equals(3)) {
                // 限时折扣
                AppDiscountGoodsQueryResultVO discountGoods = activityServiceClient.selectDiscountByGoodsIdAndTime(goodsId);
                commonIsXian = dealDiscountActivity(goodsId, goodsMaxSale, commonIsXian, activityGoodsDetail);
                if(discountGoods != null) {
                    activityGoodsDetail.setDiscountGoods(discountGoods);
                    activityGoodsDetail.setGoodsUpperLimit(discountGoods.getGoodsUpperLimit());
                    activityGoodsDetail.setActivityStartTime(discountGoods.getGoodsStartTime());
                }
            } else if (commonIsXian.equals(4)) {
                // 拼团
                commonIsXian = dealPintuanActivity(commonId, commonIsXian, goodsId, activityGoodsDetail);
            } else if (commonIsXian.equals(5)) {
                // 满减赠折
                commonIsXian = dealManjianzengzheActivity(commonId, goodsMaxSale, commonIsXian, goodsId, activityGoodsDetail);
            }else {
                commonIsXian = 0;
            }

            activityGoodsDetail.setActivityStatus(commonIsXian);
        }

        return activityGoodsDetail;
    }

    private Integer dealManjianzengzheActivity(Integer commonId,  Integer goodsMaxSale, Integer commonIsXian, Integer goodsId,
                                               ActivityGoodsDetailDTO activityGoodsDetail) {
        ManjianzengzheGoodsQueryResultVO manjianzengzheGoods = activityServiceClient.selectReductionPolicyByGoodsId(commonId);

        if (null != manjianzengzheGoods && null!=manjianzengzheGoods.getPromotionId()) {
            if (DateUtils.compareDate2(manjianzengzheGoods.getEndTime())) {
                // 剩余时间
                Long overplusTime = DateUtils.getSecondByMinusDate(new Date(), manjianzengzheGoods.getEndTime());
                activityGoodsDetail.setOverplusTime(overplusTime);
                List<ManjianzengzheGoodsRuleQueryDTO> ruleList = activityServiceClient.selectReductionPolicyRuleDetailList(manjianzengzheGoods.getPromotionId());
                activityGoodsDetail.setPromotionId(manjianzengzheGoods.getPromotionId());
                activityGoodsDetail.setRuleList(ruleList);
                activityGoodsDetail.setMjzzPrice(manjianzengzheGoods.getGoodsPrice());
                activityGoodsDetail.setGoodsLowerLimit(0);
                activityGoodsDetail.setGoodsUpperLimit(goodsMaxSale);

            } else {
                commonIsXian = 0;
            }
        } else {
            commonIsXian = 0;
        }

        return commonIsXian;
    }

    private Integer dealPintuanActivity(Integer commonId, Integer commonIsXian, Integer goodsId,
                                        ActivityGoodsDetailDTO activityGoodsDetail) {
        AppPintuanGoodsQueryResultVO pintuanGoods = activityServiceClient.selectpiecingTogetherByGoodsId(commonId, goodsId);
        if (null != pintuanGoods) {
            if (DateUtils.compareDate2(pintuanGoods.getEndTime())) {
                // 剩余时间
                Long overplusTime = DateUtils.getSecondByMinusDate(new Date(), pintuanGoods.getEndTime());
                activityGoodsDetail.setOverplusTime(overplusTime);
                activityGoodsDetail.setPintuanPrice(pintuanGoods.getPrice());
                activityGoodsDetail.setPriceOne(pintuanGoods.getPriceOne());
                activityGoodsDetail.setActivityPrice(pintuanGoods.getPrice());
            } else {
                commonIsXian = 0;
            }
            pintuanGoods.setCommonIsXian(commonIsXian);
        } else {
            commonIsXian = 0;
        }

        return commonIsXian;
    }
    private Integer dealDiscountActivity(Integer goodsId, Integer goodsMaxSale, Integer commonIsXian,
                                         ActivityGoodsDetailDTO activityGoodsDetail) {
        AppDiscountGoodsQueryResultVO discountGoods = activityServiceClient.selectDiscountByGoodsIdAndTime(goodsId);
        if (null != discountGoods) {
            if (DateUtils.compareDate2(discountGoods.getGoodsEndTime())) {
                // 剩余时间
                Long overplusTime = DateUtils.getSecondByMinusDate(new Date(), discountGoods.getGoodsEndTime());
                // 设限
                if (!discountGoods.getGoodsLowerLimit().equals(0)) {
                    activityGoodsDetail.setGoodsLowerLimit(discountGoods.getGoodsLowerLimit());
                } else {
                    activityGoodsDetail.setGoodsLowerLimit(0);
                }
                // 设限
                if (!discountGoods.getGoodsUpperLimit().equals(0)) {
                    activityGoodsDetail.setGoodsUpperLimit(discountGoods.getGoodsUpperLimit());
                } else {
                    activityGoodsDetail.setGoodsUpperLimit(goodsMaxSale);
                }
                activityGoodsDetail.setGoodsBuyCount(
                        discountGoods.getGoodsBuyCount() != null ? discountGoods.getGoodsBuyCount() : 0);
                activityGoodsDetail.setOverplusTime(overplusTime);
                activityGoodsDetail.setActivityPrice(discountGoods.getDiscountPrice());
            }
        } else {
            commonIsXian = 0;
        }
        return commonIsXian;
    }

    private Integer dealSeckillActivity(Integer goodsId, Integer goodsMaxSale, Integer commonIsXian,
                                        ActivityGoodsDetailDTO activityGoodsDetail) {
        AppSeckillGoodsQueryResultVO seckillGoods = activityServiceClient.selectSeckillByGoodsId2(goodsId);
        if (null != seckillGoods) {
            if (DateUtils.compareDate2(seckillGoods.getGoodsEndTime())) {
                // 剩余时间
                Long overplusTime = DateUtils.getSecondByMinusDate(new Date(), seckillGoods.getGoodsEndTime());

                // 设限
                if (!seckillGoods.getGoodsLowerLimit().equals(0)) {
                    activityGoodsDetail.setGoodsLowerLimit(seckillGoods.getGoodsLowerLimit());
                } else {
                    activityGoodsDetail.setGoodsLowerLimit(0);
                }
                // 设限
                if (!seckillGoods.getGoodsUpperLimit().equals(0)) {
                    activityGoodsDetail.setGoodsUpperLimit(seckillGoods.getGoodsUpperLimit());
                } else {
                    activityGoodsDetail.setGoodsUpperLimit(goodsMaxSale);
                }
                activityGoodsDetail
                        .setGoodsBuyCount(seckillGoods.getSeckillNum() != null ? seckillGoods.getSeckillNum() : 0);
                activityGoodsDetail.setOverplusTime(overplusTime);
                activityGoodsDetail.setActivityPrice(seckillGoods.getSeckillPrice());

            } else {
                commonIsXian = 0;
            }
        } else {
            commonIsXian = 0;
        }
        return commonIsXian;
    }


    @Override
    public ResponseResult queryByGoodsBaseList(ManageCommonIdsDTO param) {
        List<ManageGoodsBaseListVO> goodsBases = new ArrayList<ManageGoodsBaseListVO>();
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            goodsBases = this.baseMapper.selectByGoodsList(param.getCommonId());
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success(goodsBases);
    }

    @Override
    public ResponseResult queryByGoodsBaseList3(ManageCommonIdsDTO param) {
        List<ManageGoodsBaseListVO> goodsBases = new ArrayList<ManageGoodsBaseListVO>();
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            goodsBases = this.baseMapper.selectByGoodsList3(param.getCommonId());
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success(goodsBases);
    }

    @Override
    public ResponseResult querySeckillGoodsList(ManageCommonIdsDTO param) {
        List<ManageGoodsBaseListVO> goodsBases;
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            goodsBases = this.baseMapper.querySeckillGoodsList(param);
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success(goodsBases);
    }

    @Override
    @Transactional
    public ResponseResult updateGoodsBaseByCommonIdAndGoodsId(ManageGoodsBaseListResultDTO param){
        if(param.getCommonId() == null){
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),"commonId不能为null");
        }
        if(param.getGoodsId() == null){
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),"goodsId不能为空");
        }
        if(param.getGoodsStock() == null){
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),"库存不能为null");
        }
        //获取当前商品goods 库存
        Integer goodsStock = this.baseMapper.queryGoodsStock(param.getGoodsId());
        //增加或减少多少库存
        Integer integr = param.getGoodsStock() - goodsStock;
        if (integr>=0) {
            this.baseMapper.updateCommonStock(param.getCommonId(),integr);
        } else {
            this.baseMapper.updateCommonStock2(param.getCommonId(),integr);
        }

        Integer result = this.baseMapper.updateGoodsBaseByCommonIdAndGoodsId(param);

        GoodsCommonEntity commonEntity = goodsCommonMapper.selectOne(new LambdaQueryWrapper<GoodsCommonEntity>()
                .eq(GoodsCommonEntity::getCommonId,param.getCommonId()));
        GoodsBaseEntity baseEntity = this.baseMapper.selectOne(new LambdaQueryWrapper<GoodsBaseEntity>()
                .eq(GoodsBaseEntity::getGoodsId,param.getGoodsId()));
        if(commonEntity.getGoodsType() == 2){
            goodsCommonMapper.update(null,new LambdaUpdateWrapper<GoodsCommonEntity>()
                    .set(GoodsCommonEntity::getCommonStock,commonEntity.getCommonStock())
                    .eq(GoodsCommonEntity::getCommonParentId,commonEntity.getCommonId()));
            this.baseMapper.update(null,new LambdaUpdateWrapper<GoodsBaseEntity>()
                    .set(GoodsBaseEntity::getGoodsStock,baseEntity.getGoodsStock())
                    .eq(GoodsBaseEntity::getSupplierGoodsId,baseEntity.getGoodsId()));
        }
        return ResponseResult.success(result);
    }



    @Override
    @Transactional
    public ResponseResult newAddGoods(ManageGdsCommonPublishDTO param) {
        try {
            // 权限判断
            UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS, param.getToken());
            LOG.info(JSON.toJSONString(userPermissionsResult));
            //根据shopId查询
            GdbMerchantShopBaseVO gdbMerchantShopBase = this.baseMapper.selectByPrimaryKey(Integer.valueOf(userPermissionsResult.getShopId()));
            Integer commonId = null;
            if (userPermissionsResult.getFlag()) {

                String shopId = userPermissionsResult.getShopId();
                param.setShopId(shopId);
                param.setCommonUpdateBy(userPermissionsResult.getUserId());
                param.setCommonUpdateTime(new Date());
                // 初始化默认值
                // 判断是否放入仓库
                if (param.getCommonState() == null || param.getCommonState() == 0) {
                    param.setCommonState(0);
                }
                param.setCommonCubage(new BigDecimal(0));
                param.setGoodsId("0");
                if (gdbMerchantShopBase.getShopSelfSupport().equals("true")){
                    param.setCommonVerify(1);
                    if (param.getCommonState() != 4 && param.getCommonState() != 5) {
                        param.setCommonState(1);
                    }
                }else if(param.getCommonState() == 0){
                    param.setCommonVerify(0);
                }else if (param.getCommonState() == 5) {
                    //放入仓库修改为审核通过
                    param.setCommonVerify(1);
                }else{
                    param.setCommonVerify(10);
                }
                param.setCommonStock(0);
                param.setCommonAddTime(DateUtils.getNowDate());
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    param.setCommonSellTime(sdf.parse(param.getCommonSellTimeStr()));
                } catch (ParseException ignored) {
                }
                String image = null;
                if (!CollectionUtils.isEmpty(param.getGoodsImages())) {
                    //image = param.getGoodsImages().get(0).getImagesImage();
                    image = param.getGoodsImages().get(0).getMerchantGoodsImages().get(0).getImagesImage();
                    param.setCommonImage(image);
                }
                // 获取店铺区域id
                ManageShopBaseQueryVO shopBaseQueryResult = shopBaseMapper.selectByShopId2(param.getShopId());

                param.setDistrictId(shopBaseQueryResult.getDistrictId());
                param.setShopName(shopBaseQueryResult.getShopName());
                if (shopBaseQueryResult.getShopSelfSupport() == "false") {
                    param.setShopSelfSupport(0);
                } else {
                    param.setShopSelfSupport(1);
                }
                // 判断主图类型
                if (StringUtils.isNotEmpty(param.getCommonVideo())) {
                    param.setType(2);
                }

                param.setShopStatus(shopBaseQueryResult.getShopStatus());
                param.setCommonSpecValue("");
                // 将规格 和 规格值保存到数据库 规格跟着商品走
                param.setSpecParamJson(JSON.toJSONString(param.getSpecParam()));
                if (null != userPermissionsResult.getShopType()){
                    if (userPermissionsResult.getShopType().equals(CommonType.ShopType.SUPPLY_SHOP.getCode())) {
                        param.setGoodsType(2);
                    }
                }
                //品牌店铺商品类型为3
                if (gdbMerchantShopBase.getShopType() == 3){
                    param.setGoodsType(3);
                }
                if (null == param.getVirtualGoods()) {
                    param.setVirtualGoods(1);
                }
                if (!StringUtils.isNotBlank(param.getPeriodOfValidity())) {
                    param.setPeriodOfValidity(null);
                }
                //获取传来的门店id数组
                List<Integer> storeId = param.getStoreId();
                //转化为字符串存储到数据库
                String storeIds = StringUtils.join(storeId, ",");
                param.setGoodsAssignmentStore(storeIds);
                param.setBrandId(param.getBrandId());
                param.setBrandName(param.getBrandName());
                //店铺商品分类
                String join = Joiner.on(",").join(param.getGoodsCatIdList());
                System.out.println(join);
                param.setGoodsCatIds(join);
                // 添加数据到公共信息表,并获取common_id
                goodsCommonMapper.newInsertGdsCommonObj(param);
                LOG.info("商品common表更新成功，common_id = {}", param.getCommonId());
                commonId = param.getCommonId();

                //属性id和属性内容id存储中间表
                param.setCommonId(commonId);
                List<AttributeParamDTO> attributeIds=param.getAttribuParam();//前端传值商品属性id
                //通过商品属性id查询属性内容然后添加对应的属性内容id
                if(null != attributeIds && attributeIds.size()>0){
                    for(AttributeParamDTO attribu:attributeIds){
                        Integer attrConIds=attribu.getAttributeContentId();
                        param.setButeId(attrConIds);
                        param.setAttribuId(attribu.getAttributeId());
                        goodsCommonAttributeAssociationMapper.insertAss(param);
                    }
                }


                List<HotGoodsDTO> hotGoodsDTOList = null;
//                if (param.getHotState().intValue() == 1) {
//                    // 爆品集合
//                    hotGoodsList = new ArrayList<>();
//                }
                int num = 0;
                GdbNavSortLogoDTO gdbNavSortLogoDTO = new GdbNavSortLogoDTO();
                gdbNavSortLogoDTO.setConfigKey("logo_copywriting_ico_goods");
                gdbNavSortLogoDTO.setConfigType("logo_copywriting");
                List<WebNavLogoConbfigDTO> webNavLogoConbfigDTOList = baseSysConfigsMapper.quertNavLogoByConfigType(gdbNavSortLogoDTO);
                // 获取goods_base,赋值commomid
                List<ManageGdsBaseAddPublishDTO> gdsBases = param.getGdsBases();
                for (int k = 0; k < gdsBases.size(); k++) {
                    ManageGdsBaseAddPublishDTO gdsBase = gdsBases.get(k);
                    gdsBase.setGoodsPromotionTips(param.getCommonPromotionTips());
                    gdsBase.setCommonId(commonId);
                    gdsBase.setShopId(shopId);
                    gdsBase.setShopName(shopBaseQueryResult.getShopName());
                    gdsBase.setGoodsIsRecommend(param.getCommonIsRecommend());
                    gdsBase.setGoodsImage(param.getGoodsImages().get(k).getMerchantGoodsImages().get(0).getImagesImage());

                    if (gdsBase.getBrandId() == null) {
                        gdsBase.setBrandId(0);
                    }
                    if (gdsBase.getGoodsAlarm() == null) {
                        gdsBase.setGoodsAlarm(0);
                    }
                    if (gdsBase.getGoodsMaxSale() == null) {
                        gdsBase.setGoodsMaxSale(0);
                    }

                    ManageGdsBaseAddParamvDTO manageGdsBaseAddParam = new ManageGdsBaseAddParamvDTO();
                    manageGdsBaseAddParam.setSpecId(gdsBase.getSpecId());
                    manageGdsBaseAddParam.setTypeId(gdsBase.getTypeId());
                    if (StringUtils.isNotBlank(gdsBase.getGoodsSpec())) {
                        manageGdsBaseAddParam.setGoodsName(gdsBase.getGoodsName() + "(" + gdsBase.getGoodsSpec() + ")");
                    } else {
                        manageGdsBaseAddParam.setGoodsName(gdsBase.getGoodsName());
                    }
                    String goodsSpecValueVar = this.baseMapper.selectByGoodsSpecValue(manageGdsBaseAddParam);
                    System.out.println(goodsSpecValueVar);
                    //带查询

                    manageGdsBaseAddParam.setGoodsId(gdsBase.getGoodsId());
                    manageGdsBaseAddParam.setCommonId(gdsBase.getCommonId());
                    manageGdsBaseAddParam.setShopId(gdsBase.getShopId());
                    manageGdsBaseAddParam.setShopName(gdsBase.getShopName());
                    manageGdsBaseAddParam.setGoodsPromotionTips(gdsBase.getGoodsPromotionTips());
                    manageGdsBaseAddParam.setCatId(gdsBase.getCatId());
                    manageGdsBaseAddParam.setGoodsSpecValue(gdsBase.getGoodsSpecValue());
                    manageGdsBaseAddParam.setGoodsPrice(gdsBase.getGoodsPrice());
                    manageGdsBaseAddParam.setGoodsMarketPrice(gdsBase.getGoodsMarketPrice());
                    manageGdsBaseAddParam.setGoodsStock(gdsBase.getGoodsStock());
                    //添加门店库存总和最大值
                    manageGdsBaseAddParam.setGoodsShopGateStock(gdsBase.getGoodsShopGateStock());
                    manageGdsBaseAddParam.setGoodsAlarm(gdsBase.getGoodsAlarm());
                    manageGdsBaseAddParam.setGoodsCode(gdsBase.getGoodsCode());
                    manageGdsBaseAddParam.setGoodsBarcode(gdsBase.getGoodsBarcode());
                    manageGdsBaseAddParam.setGoodsIsRecommend(gdsBase.getGoodsIsRecommend());
                    manageGdsBaseAddParam.setGoodsImage(gdsBase.getGoodsImage());
                    manageGdsBaseAddParam.setGoodsIsShelves(gdsBase.getGoodsIsShelves());
                    manageGdsBaseAddParam.setBrandId(gdsBase.getBrandId());
                    manageGdsBaseAddParam.setGoodsCubage(gdsBase.getGoodsCubage());
                    manageGdsBaseAddParam.setGoodsBabyPrice(gdsBase.getGoodsBabyPrice());
                    manageGdsBaseAddParam.setGoodsMinSale(gdsBase.getGoodsMinSale());
                    //规格跟着商品走
                    manageGdsBaseAddParam.setIsUse(gdsBase.getIsUse());
                    // 商家编号
                    manageGdsBaseAddParam.setMerchantCode(gdsBase.getMerchantCode());
                    // 商品编码
                    manageGdsBaseAddParam.setCommodityBarTypeCode(gdsBase.getCommodityBarTypeCode());
                    // 规格
                    manageGdsBaseAddParam.setSpecValue(JSON.toJSONString(gdsBase.getSpecValues()));
                    //指导价
                    manageGdsBaseAddParam.setHotPrice(gdsBase.getHotPrice());
                    List<GoodBaseSpecValuesJsonBeanDTO> specValues = gdsBase.getSpecValues();
                    String goodsSpec = null;
                    for (GoodBaseSpecValuesJsonBeanDTO specValue : specValues) {
                        if (goodsSpec == null) {
                            goodsSpec = specValue.getParamValue();
                            continue;
                        }
                        goodsSpec = goodsSpec + "+" + specValue.getParamValue();
                    }
                    manageGdsBaseAddParam.setGoodsSpec(goodsSpec);
                    // 体积
                    if (StringUtils.isNotEmpty(gdsBase.getGoodsVolume())) {
                        BigDecimal goodsVolume = new BigDecimal(gdsBase.getGoodsVolume());
                        manageGdsBaseAddParam.setGoodsVolume(goodsVolume);
                    }
                    // 商品成本价
                    if (null != param.getCommonCostPrice()) {
                        manageGdsBaseAddParam.setGoodsCostPrice(param.getCommonCostPrice());
                    }
                    // 直播卖点
                    if (StringUtils.isNotEmpty(param.getSellingPoint())) {
                        manageGdsBaseAddParam.setSellingPoint(param.getSellingPoint());
                    }
                    // 是否寄样
                    if (null != gdsBase.getGoodsSendBack()) {
                        manageGdsBaseAddParam.setGoodsSendBack(gdsBase.getGoodsSendBack());
                    }
                    //限购不设置 则默认最多购买数量是商品的库存
                    manageGdsBaseAddParam.setGoodsMaxSale(gdsBase.getGoodsMaxSale());
                    if (null == gdsBase.getGoodsMaxSale() || 0 == gdsBase.getGoodsMaxSale()) {
                        manageGdsBaseAddParam.setGoodsMaxSale(gdsBase.getGoodsStock());
                    }
                    if (null != gdsBase.getCommission()) {
                        manageGdsBaseAddParam.setCommission(gdsBase.getCommission());
                    }
                    this.baseMapper.insertGdsBasesObj(manageGdsBaseAddParam);
                    Integer goodsId = this.baseMapper.getByGoodsId();
                    System.out.println(goodsId);
                    gdsBase.setGoodsId(goodsId);
                    //设置爆品
                    if (null != hotGoodsDTOList && gdsBase.getHotPrice().compareTo(BigDecimal.ZERO) > 0) {
                        HotGoodsDTO hotGoodsDTO = new HotGoodsDTO(gdsBase);
                        hotGoodsDTOList.add(hotGoodsDTO);
                    }


                    // 添加商品图片
                    List<GdbMerchantGuiGeGoodsImagesDTO> goodsImages = param.getGoodsImages();
                    if (!CollectionUtils.isEmpty(goodsImages)) {
                        for (GdbMerchantGoodsImagesVO goodsImage : goodsImages.get(num).getMerchantGoodsImages()) {
                            if (goodsImage.getImagesDisplayorder() == null) {
                                goodsImage.setImagesDisplayorder(0);
                            }
                            if (goodsImage.getImagesIsDefault() == null) {
                                goodsImage.setImagesIsDefault(1);
                            }
                            goodsImage.setGoodsId(goodsId);
                            goodsImage.setShopId(shopId);
                            goodsImage.setCommonId(commonId);
                        }
                    } else {
                        GdbMerchantGoodsImagesVO goodsImage = new GdbMerchantGoodsImagesVO();
                        if (goodsImage.getImagesDisplayorder() == null) {
                            goodsImage.setImagesDisplayorder(0);
                        }
                        if (goodsImage.getImagesIsDefault() == null) {
                            goodsImage.setImagesIsDefault(1);
                        }
                        goodsImage.setGoodsId(goodsId);
                        goodsImage.setShopId(shopId);
                        goodsImage.setCommonId(commonId);
                        goodsImages.get(num).getMerchantGoodsImages().add(goodsImage);
                    }

                    if (null != goodsImages && !goodsImages.isEmpty()) {
                        for (GdbMerchantGoodsImagesVO recordImage : goodsImages.get(num).getMerchantGoodsImages()) {
                            if (!recordImage.getImagesImage().equals(webNavLogoConbfigDTOList.get(0).getConfigValue())) {
                                recordImage.setImagesId(null);
                                goodsImagesMapper.insertSelective(recordImage);
                            }
                        }
                        num++;
                    }
                    LOG.info("商品common_images表更新成功");
                }

                if (!CollectionUtils.isEmpty(hotGoodsDTOList)) {
                    goodsHotMapper.insertHotGoodsBatch(hotGoodsDTOList);
                    LOG.info("添加爆品成功");
                }
                // 添加goods_base
                LOG.info("商品goods_base表更新成功");

                // 添加商品属性表
                String commonProperty = param.getCommonProperty();
                if (!StringUtils.isEmpty(commonProperty)) {
                    List<ManageGoodsPropertyAddDTO> propertys = JSON.parseArray(commonProperty, ManageGoodsPropertyAddDTO.class);
                    if (propertys.size() > 0) {
                        for (ManageGoodsPropertyAddDTO property : propertys) {
                            property.setCommonId(commonId);
                        }
                        goodsPropertyIndexMapper.insertBatch(propertys);
                    }

                }
                // 添加商品详情
                GdbMerchantGoodsCommonDetailDTO goodsCommonDetail = param.getGoodsCommonDetail();
                if (null != goodsCommonDetail) {
                    goodsCommonDetail.setCommonId(commonId);
                    goodsCommonDetailMapper.insertSelective(goodsCommonDetail);
                    LOG.info("商品common_detail表更新成功");
                }
                //多规格需求 2020/10/15
                // 更新商品规格
                String commonSpecName = param.getCommonSpecName();
                List<String> result = Arrays.asList(commonSpecName.split(","));
                for (String specNameVar : result) {
                    System.out.println(specNameVar);
//                List<ManageGdsBaseAdd> gdsBaseListResult = new ArrayList<>();
//                for (ManageGdsBaseAdd gdsBaseList : gdsBases) {
//                    if(specNameVar.equals(gdsBaseList.getSpecId())){
//                        gdsBaseListResult.add(gdsBaseList);
//                    }
//
//                }
                    // 更新商品规格
                    newUpdateCommonSpec(commonId, gdsBases, specNameVar);
                    System.out.println("调用方法");

                }
                if (null != param.getManageGdsGoodsConfig()) {
                    // 保存经销商品配置信息数据
                    BaseGoodsConfigVO manageGdsGoodsConfig = param.getManageGdsGoodsConfig();
                    manageGdsGoodsConfig.setCommonId(commonId);
                    goodsDelayConfigMapper.insertSelective(manageGdsGoodsConfig);
                }
                if (!CollectionUtils.isEmpty(param.getGoodsCatIdList())) {
                    List<MerchantShopGoodsCatDTO> goodsCatList = shopSelfCatMapper.queryShopCatIds(param.getGoodsCatIdList());
                    for (MerchantShopGoodsCatDTO shopGoodsCat : goodsCatList) {
                        shopGoodsCat.setCommonId(commonId);
                        shopGoodsCat.setShopId(Integer.valueOf(userPermissionsResult.getShopId()));
                        shopGoodsCat.setParentId(null == shopGoodsCat.getParentId() ? 0 : shopGoodsCat.getParentId());
                    }
                    shopGoodsCatMapper.insertSelectiveBatch(goodsCatList);
                }
            } else {
                return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
            }
            return ResponseResult.success(commonId);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.OPERATION_FAILED.getMsg());
        }
    }



    private void newUpdateCommonSpec(Integer commonId, List<ManageGdsBaseAddPublishDTO> addGoodsBases, String commonSpecName) {
        List<CommonSpecValueDTO> commonSpecValues = Lists.newArrayList();
        Integer commonStock = 0;
        // 更新goods_common中规格
        UpdateGdsSpecParamDTO updateGdsSpecParam = new UpdateGdsSpecParamDTO();
//        Collections.sort(addGoodsBases, new Comparator<ManageGdsBaseAddPublish>() {
//
//            @Override
//            public int compare(ManageGdsBaseAddPublish o1, ManageGdsBaseAddPublish o2) {
//
//                // 按照商品价格进行升序排列
//                if (o1.getGoodsPrice().compareTo(o2.getGoodsPrice()) == 1) {
//                    return 1;
//                }
//                if (o1.getGoodsPrice().compareTo(o2.getGoodsPrice()) == 0) {
//                    return 0;
//                }
//                return -1;
//            }
//        });

        for (ManageGdsBaseAddPublishDTO goodsBase : addGoodsBases) {
            ManageGdsBaseAddParamvDTO manageGdsBaseAddParam =new ManageGdsBaseAddParamvDTO();
            manageGdsBaseAddParam.setGoodsSpec(goodsBase.getGoodsName());
            manageGdsBaseAddParam.setSpecId(goodsBase.getSpecId());
            manageGdsBaseAddParam.setTypeId(goodsBase.getTypeId());

//            GoodsReleasedParam goodsReleasedParam= goodsCommonMapper.selectGoodsReleasedParam(manageGdsBaseAddParam);
            CommonSpecValueDTO value = new CommonSpecValueDTO();
            value.setCommonId(commonId);
            value.setGoodsId(goodsBase.getGoodsId());
//            value.setGoodsSpecId(Integer.parseInt(goodsReleasedParam.getSpecValueId()));
//            value.setSpecNameId(Integer.parseInt(goodsReleasedParam.getSpecId()));
            commonStock = commonStock + goodsBase.getGoodsStock();
            commonSpecValues.add(value);
        }
        ManageGdsBaseAddPublishDTO manageGdsBase = addGoodsBases.get(0);
        updateGdsSpecParam.setCommonSpecValue(JSON.toJSONString(commonSpecValues));
        updateGdsSpecParam.setCommonStock(commonStock);
        updateGdsSpecParam.setCommonShopGateStock(commonStock/2);
        //查询goodsId
        updateGdsSpecParam.setGoodsId(manageGdsBase.getGoodsId().toString());
        updateGdsSpecParam.setCommonPrice(manageGdsBase.getGoodsPrice());
        updateGdsSpecParam.setCommonMarketPrice(manageGdsBase.getGoodsMarketPrice());
        updateGdsSpecParam.setCommonImage(manageGdsBase.getGoodsImage());
        updateGdsSpecParam.setCommonAlarm(manageGdsBase.getGoodsAlarm());
        updateGdsSpecParam.setCommonCubage(manageGdsBase.getGoodsCubage());
        updateGdsSpecParam.setCommonId(commonId);
        updateGdsSpecParam.setCommonBabyPrice(manageGdsBase.getGoodsBabyPrice());
        updateGdsSpecParam.setTypeId(manageGdsBase.getTypeId());

        goodsCommonMapper.updateGdsSpec(updateGdsSpecParam);
        LOG.info("更新common表规格商品信息成功");
    }



    @Override
    @Transactional
    public ResponseResult updateGoods(ManageGdsCommonUpdateDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            Map<String,Object> map= new HashMap<>();
            List<Integer> list = new ArrayList<>();
            list.add(param.getCommonId());
            //通过mq 更新es的商品数据
            map.put("commonIdS",list);
            Integer num = 0;

            String shopId = userPermissionsResult.getShopId();

            // 查询店铺名称
            String shopName = shopBaseMapper.selectShopName(Integer.valueOf(shopId));
            param.setShopName(shopName);
            param.setShopId(shopId);
            param.setCommonCubage(new BigDecimal(0));
            Integer commonId = param.getCommonId();

            if (param.getCommonState() == null || param.getCommonState() == 0) {
                param.setCommonState(0);
            }

            // 判断主图类型
            if (StringUtils.isNotEmpty(param.getCommonVideo())) {
                param.setType(2);
            }

            // 获取公共信息表规格值和goodsid
            List<ManageGdsBaseAddParamvDTO> gdsBases = param.getGdsBases();
            List<ManageGdsBaseAddParamvDTO> addGoodsBases = Lists.newArrayList();
            List<ManageGdsBaseAddParamvDTO> updateGoodsBases = Lists.newArrayList();
            List<GdbMerchantGuiGeGoodsImagesDTO> addImages = Lists.newArrayList();
            List<GdbMerchantGuiGeGoodsImagesDTO> updateImages = Lists.newArrayList();
            List<Integer> removeGoodsImage = Lists.newArrayList();
            List<Integer> updateGoodsStatus = Lists.newArrayList();
            String image = null;
            Integer commonStock = 0;
            if (!CollectionUtils.isEmpty(param.getGoodsImages())) {
                //image = param.getGoodsImages().get(0).getImagesImage();
                image = param.getGoodsImages().get(0).getMerchantGoodsImages().get(0).getImagesImage();
                param.setCommonImage(image);
            }
            if (!CollectionUtils.isEmpty(gdsBases)) {
                String goodsImg = null;
                List<GdbMerchantGuiGeGoodsImagesDTO> goodsImages = param.getGoodsImages();
                for (ManageGdsBaseAddParamvDTO gdsBase : gdsBases) {
                    //获取sku图片
                    goodsImg = goodsImages.get(num).getMerchantGoodsImages().get(0).getImagesImage();
                    gdsBase.setImg(goodsImages.get(num).getMerchantGoodsImages());
                    System.out.println("商品sku图片++" + goodsImages.get(num).getMerchantGoodsImages());

                    gdsBase.setGoodsPromotionTips(param.getCommonPromotionTips());
                    if (null == param.getBrandId()) {
                        gdsBase.setBrandId(0);
                    }

                    if (param.getCommonState().equals(1)) {
                        gdsBase.setGoodsIsShelves(1);
                    } else {
                        gdsBase.setGoodsIsShelves(2);
                    }
//					gdsBase.setGoodsName(param.getCommonName());
                    commonStock += gdsBase.getGoodsStock();
                    gdsBase.setGoodsStock(gdsBase.getGoodsStock());
                    gdsBase.setGoodsShopGateStock(gdsBase.getGoodsShopGateStock());
                    gdsBase.setGoodsImage(goodsImg);
                    gdsBase.setGoodsIsRecommend(param.getCommonIsRecommend());
                    gdsBase.setCommonId(commonId);
                    gdsBase.setShopId(shopId);
                    gdsBase.setGoodsCostPrice(param.getCommonCostPrice());
                    List<GoodBaseSpecValuesJsonBeanDTO> specValues = gdsBase.getSpecValues();
                    String goodsSpec = null;
                    for (GoodBaseSpecValuesJsonBeanDTO specValue : specValues) {
                        if(goodsSpec==null){
                            goodsSpec = specValue.getParamValue();
                            continue;
                        }
                        goodsSpec = goodsSpec+"+"+specValue.getParamValue();
                    }
                    gdsBase.setGoodsSpec(goodsSpec);
                    gdsBase.setShopName(shopName);
                    gdsBase.setSpecValue(JSON.toJSONString(specValues));
                    if (null == gdsBase.getGoodsId()) {
                        addGoodsBases.add(gdsBase);
                    } else {
                        updateGoodsStatus.add(gdsBase.getGoodsId());
                        updateGoodsBases.add(gdsBase);
                    }
                    // 爆品设置
//					hotServiceImpl.hotGoodsUpdate(param.getHotState(), gdsBase);
                    num++;
                }
            } else {
                return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),"规格不能为空");
            }

            for (GdbMerchantGuiGeGoodsImagesDTO images : param.getGoodsImages()) {
                boolean flag = true;
                for (GdbMerchantGoodsImagesVO img : images.getMerchantGoodsImages()) {
                    if (img.getImagesId() != null) {
                        removeGoodsImage.add(img.getImagesId());
                        flag = false;
                    }
                }
            }
            //删除图片
            if (!CollectionUtils.isEmpty(removeGoodsImage)) {
                goodsImagesMapper.deleteByGoodsImageIds(removeGoodsImage, commonId);
            }

            param.setCommonUpdateBy(userPermissionsResult.getUserId());
            param.setCommonUpdateTime(new Date());
            param.setCommonPrice(gdsBases.get(0).getGoodsPrice());
            // 修改状态为审核中
            param.setCommonVerify(10);
            param.setCommonPrice(gdsBases.get(0).getGoodsPrice());
            param.setSpecParamJson(JSONObject.toJSONString(param.getSpecParam()));

            //根据shopId查询
            GdbMerchantShopBaseVO gdbMerchantShopBase = this.baseMapper.selectByPrimaryKey(Integer.valueOf(userPermissionsResult.getShopId()));
            if (gdbMerchantShopBase.getShopSelfSupport().equals("true")){
                param.setShopSelfSupport(2);
                param.setCommonVerify(1);
            }else{
                param.setShopSelfSupport(1);
            }

            // 插入数据到公共信息表,并获取common_id
            param.setCommonStock(commonStock);

            param.setBrandId(param.getBrandId());
            param.setBrandName(param.getBrandName());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (param.getPeriodOfValidity() != null && param.getPeriodOfValidity() != ""){
                try {
                    param.setPeriodOfValiditys(format.parse(param.getPeriodOfValidity()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

            goodsCommonMapper.updateGdsCommonObj(param);

            //编辑发布商品时先删除商品属性关联表里的数据再添加
            goodsCommonAttributeAssociationMapper.deleteAsscon(param.getCommonId());
            List<AttributeParamDTO> attributeIds=param.getAttribuParam();//前端传值商品属性id
            //通过商品属性id查询属性内容然后添加对应的属性内容id
            if(null != attributeIds &&  attributeIds.size()>0){
                for(AttributeParamDTO attribu:attributeIds){
                    Integer attrConIds=attribu.getAttributeContentId();
                    param.setButeId(attrConIds);
                    param.setAttribuId(attribu.getAttributeId());
                    goodsCommonAttributeAssociationMapper.insertAssContent(param);
                }
            }



            LOG.info("更新common表成功");
            // 更新商品状态
            this.baseMapper.updateGoodsIsShelves2(updateGoodsStatus, commonId);

            // 添加goods_base
            if (!CollectionUtils.isEmpty(addGoodsBases)) {
                for (ManageGdsBaseAddParamvDTO addGoodsBase : addGoodsBases) {
                    this.baseMapper.insertGdsBasesObj(addGoodsBase);
                    System.out.println("新加规格的goodsId-----" + addGoodsBase.getGoodsId());

                    // 添加商品图片
                    List<GdbMerchantGoodsImagesVO> goodsImages = addGoodsBase.getImg();
                    List<GdbMerchantGoodsImagesVO> addImgs = Lists.newArrayList();
                    if (!CollectionUtils.isEmpty(goodsImages)) {
                        for (GdbMerchantGoodsImagesVO goodsImage : goodsImages) {
                            goodsImage.setCommonId(param.getCommonId());
                            goodsImage.setShopId(shopId);
                            goodsImage.setGoodsId(addGoodsBase.getGoodsId());
                            addImgs.add(goodsImage);
                        }

                        goodsImagesMapper.insertBatch(addImgs);
                        LOG.info("更新common_images表成功");
                    }
                }
            }
            if (!CollectionUtils.isEmpty(updateGoodsBases)) {
                for(ManageGdsBaseAddParamvDTO record : updateGoodsBases) {
                    if( null == record.getGoodsMaxSale()  || 0  == record.getGoodsMaxSale()){
                        record.setGoodsMaxSale(record.getGoodsStock());
                    }
                    this.baseMapper.updateGdsBasesBatch2Obj(record);

                    // 添加商品图片
                    List<GdbMerchantGoodsImagesVO> img = record.getImg();
                    List<GdbMerchantGoodsImagesVO> addImgs = Lists.newArrayList();
                    List<GdbMerchantGoodsImagesVO> upImgs = Lists.newArrayList();
                    if (!CollectionUtils.isEmpty(img)) {
                        for (GdbMerchantGoodsImagesVO goodsImage : img) {
                            if (goodsImage.getImagesId() == null){
                                goodsImage.setCommonId(param.getCommonId());
                                goodsImage.setShopId(shopId);
                                goodsImage.setGoodsId(record.getGoodsId());
                                goodsImage.setImagesDisplayorder(0);
                                goodsImage.setImagesIsDefault(0);
                                addImgs.add(goodsImage);
                            }else{
                                goodsImage.setCommonId(param.getCommonId());
                                goodsImage.setShopId(shopId);
                                goodsImage.setGoodsId(record.getGoodsId());
                                upImgs.add(goodsImage);
                            }

                        }
                        if (!CollectionUtils.isEmpty(upImgs)){
                            goodsImagesMapper.updateBatch(upImgs);
                        }
                        if (!CollectionUtils.isEmpty(addImgs)){
                            addImgs.get(0).setImagesIsDefault(1);
                            goodsImagesMapper.insertBatch(addImgs);
                        }


                        LOG.info("更新common_images表成功");
                    }
                }
            }

            LOG.info("更新goods_base表成功");

            addGoodsBases.addAll(updateGoodsBases);
            String commonSpecName = param.getCommonSpecName();
            // 更新商品规格
            updateCommonSpec2(commonId, addGoodsBases, commonSpecName);

            // 添加商品详情
            GdbMerchantGoodsCommonDetailDTO goodsCommonDetail = param.getGoodsCommonDetail();
            if (null != goodsCommonDetail) {

                GdbMerchantGoodsCommonDetailVO selectByPrimaryKey = goodsCommonDetailMapper.selectByPrimaryKey(commonId);
                goodsCommonDetail.setCommonId(commonId);
                if (null != selectByPrimaryKey) {
                    goodsCommonDetailMapper.updateByPrimaryKeySelective(goodsCommonDetail);
                } else {
                    goodsCommonDetailMapper.insertSelective(goodsCommonDetail);
                }

            }

            LOG.info("更新common_detail表成功");

            // 添加商品属性表
            goodsPropertyIndexMapper.deleteByShopId(commonId);
            String commonProperty = param.getCommonProperty();
            if (null != commonProperty && !commonProperty.equals("")) {
                List<ManageGoodsPropertyAddDTO> propertys = JSON.parseArray(commonProperty, ManageGoodsPropertyAddDTO.class);
                if (propertys.size() > 0) {
                    for (ManageGoodsPropertyAddDTO property : propertys) {
                        property.setCommonId(commonId);
                    }
                    goodsPropertyIndexMapper.insertBatch(propertys);
                }

            }
            LOG.info("更新common_property表成功");

            // 更新经销商品配置信息
            if (null != param.getManageGdsGoodsConfig()) {

                BaseGoodsConfigVO config = goodsDelayConfigMapper.selectByPrimaryKey(param.getCommonId());
                if (null != config) {
                    config = param.getManageGdsGoodsConfig();
                    config.setCommonId(param.getCommonId());
                    goodsDelayConfigMapper.updateByPrimaryKeySelective(config);
                } else {
                    config = param.getManageGdsGoodsConfig();
                    config.setCommonId(param.getCommonId());
                    goodsDelayConfigMapper.insertSelective(config);
                }
            }
            if (!CollectionUtils.isEmpty(param.getGoodsCatIdList())) {

                //更新店铺商品分类
                shopGoodsCatMapper.deleteByCommonId(param.getCommonId());

                List<MerchantShopGoodsCatDTO> goodsCatList = shopSelfCatMapper.queryShopCatIds(param.getGoodsCatIdList());

                for (MerchantShopGoodsCatDTO shopGoodsCat : goodsCatList) {

                    shopGoodsCat.setCommonId(commonId);
                    shopGoodsCat.setShopId(Integer.valueOf(userPermissionsResult.getShopId()));
                    shopGoodsCat.setParentId(null == shopGoodsCat.getParentId() ? 0 : shopGoodsCat.getParentId());
                }
                if (null != goodsCatList && goodsCatList.size() != 0) {
                    shopGoodsCatMapper.insertSelectiveBatch(goodsCatList);
                }
            }
            List<Integer> supperCommonId = new ArrayList<>();
            for (Integer SuppercommonId : list) {
                //判断当前是否是是供应商商品 如果是 下架商家对应的商品 并更新es
                List<Integer> dealerCommonIds = goodsCommonMapper.queryIsSupperGoods(SuppercommonId);
                if(null != dealerCommonIds && dealerCommonIds.size() >0 ){
                    //当前商品是供应商商品 所有商家商品下架 更新es
                    goodsCommonMapper.updateOffline(dealerCommonIds);
                }
                supperCommonId.addAll(dealerCommonIds);
            }
            list.addAll(supperCommonId);
            // 1 是添加  2是删除
            map.put("type",2);
            MqSendUtils.mqSendGoods(map);
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success();

    }


    private void updateCommonSpec2(Integer commonId, List<ManageGdsBaseAddParamvDTO> addGoodsBases, String commonSpecName) {
        List<CommonSpecValueDTO> commonSpecValues = Lists.newArrayList();
        Integer commonStock = 0;
        // 更新goods_common中规格
        UpdateGdsSpecParamDTO updateGdsSpecParam = new UpdateGdsSpecParamDTO();
//		Collections.sort(addGoodsBases, new Comparator<ManageGdsBaseAddParam>() {
//
//			@Override
//			public int compare(ManageGdsBaseAddParam o1, ManageGdsBaseAddParam o2) {
//
//				// 按照商品价格进行升序排列
//				if (o1.getGoodsPrice().compareTo(o2.getGoodsPrice()) == 1) {
//					return 1;
//				}
//				if (o1.getGoodsPrice().compareTo(o2.getGoodsPrice()) == 0) {
//					return 0;
//				}
//				return -1;
//			}
//		}
//		);

        for (ManageGdsBaseAddParamvDTO goodsBase : addGoodsBases) {
            ManageGdsBaseAddParamvDTO manageGdsBaseAddParam =new ManageGdsBaseAddParamvDTO();
            manageGdsBaseAddParam.setGoodsSpec(goodsBase.getGoodsName());
            manageGdsBaseAddParam.setSpecId(goodsBase.getSpecId());
            manageGdsBaseAddParam.setTypeId(goodsBase.getTypeId());

            GoodsReleasedVO goodsReleasedParam= goodsSpecValueMapper.selectGoodsReleasedParam(manageGdsBaseAddParam);
            CommonSpecValueDTO value = new CommonSpecValueDTO();
            value.setCommonId(commonId);
            value.setGoodsId(goodsBase.getGoodsId());
//			value.setGoodsSpecId(Integer.parseInt(goodsReleasedParam.getSpecValueId()));
//			value.setSpecNameId(Integer.parseInt(goodsReleasedParam.getSpecId()));
            commonStock = commonStock + goodsBase.getGoodsStock();
            commonSpecValues.add(value);
        }
        ManageGdsBaseAddParamvDTO manageGdsBase = addGoodsBases.get(0);
        updateGdsSpecParam.setCommonSpecValue(JSON.toJSONString(commonSpecValues));
        updateGdsSpecParam.setCommonStock(commonStock);
        //查询goodsId
        updateGdsSpecParam.setGoodsId(manageGdsBase.getGoodsId().toString());
        updateGdsSpecParam.setCommonPrice(manageGdsBase.getGoodsPrice());
        updateGdsSpecParam.setCommonMarketPrice(manageGdsBase.getGoodsMarketPrice());
        updateGdsSpecParam.setCommonImage(manageGdsBase.getGoodsImage());
        updateGdsSpecParam.setCommonAlarm(manageGdsBase.getGoodsAlarm());
        updateGdsSpecParam.setCommonCubage(manageGdsBase.getGoodsCubage());
        updateGdsSpecParam.setCommonId(commonId);
        updateGdsSpecParam.setCommonBabyPrice(manageGdsBase.getGoodsBabyPrice());
        updateGdsSpecParam.setTypeId(manageGdsBase.getTypeId());

        goodsCommonMapper.updateGdsSpec(updateGdsSpecParam);
        LOG.info("更新common表规格商品信息成功");
    }



    @Override
    public ResponseResult queryGoods(ManageCommonIdsDTO param) {
        ManageGdsCommonQueryVO commonResult = new ManageGdsCommonQueryVO();
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            Integer commonId = param.getCommonId();
            String shopId = userPermissionsResult.getShopId();

            // 返回结果
            ManageGdsCommonVO common = goodsCommonMapper.selectByCommonId2(commonId);

            if (StringUtils.isNotEmpty(common.getSpecParam())) {
                List<SpecParamJsonBeanVO> list = new ArrayList<>();
                JSONArray jsonSpecParam = JSONObject.parseArray(common.getSpecParam());
                for(int index = 0;index < jsonSpecParam.size();index++) {
                    JSONObject obj = jsonSpecParam.getJSONObject(index);
                    SpecParamJsonBeanVO temp = JSONObject.parseObject(obj.toJSONString(), SpecParamJsonBeanVO.class);
                    list.add(temp);
                }
                common.setSpecParamList(list);
            }


            List<GdbAttributeAssionParamVO> assionParams=goodsCommonAttributeAssociationMapper.selectCommonIds(commonId);
            for(GdbAttributeAssionParamVO assionParam : assionParams){
                GoodsAttributeVO gdbAttrPram=goodsAttributeMapper.selectAttributeId(assionParam.getAttributeId());
                if (gdbAttrPram != null) {
                    assionParam.setAttributeIds(gdbAttrPram.getCommodityAttribute());
                }
                GoodsAttributeVO gdbAttrPram1=goodsAttributeContentMapper.selectAttContentId(assionParam.getAttributeContentId());
                if (gdbAttrPram1 != null) {
                    assionParam.setAttributeContentIds(gdbAttrPram1.getAttriContent());
                }
            }
            commonResult.setGdbAttributeAssionParams(assionParams);


            // 设置运费和售卖区域
            ManageTransportTemplateVO transportTemplate = shopTransportTemplateMapper
                    .selectById(common.getTransportTemplate());

            ManageTransportAreaVO transportAreas = shopTransportAreaMapper.selectById(common.getTransportAreaId());
            common.setTransportTemplates(transportTemplate);
            common.setTransportAreas(transportAreas);
            // 规格跟着商品走
            if(StringUtils.isEmpty(common.getSpecParam())) {
                // 查询规格名称
                List<ManageSpecNameVO> goodsSpec = goodsSpecMapper.selectByTypeId(common.getTypeId());
                common.setCommonSpecNameList(goodsSpec);
                // 查询规格值
                ManageSpecValueVO specValueQuery = new ManageSpecValueVO();
                specValueQuery.setShopId(shopId);
                specValueQuery.setCatId(common.getCatId());
                specValueQuery.setTypeId(common.getTypeId());
                List<ManageSpecValueResultVO> specValueList = goodsSpecValueMapper.selectByShopId2(specValueQuery);
                List<ManageSpecValueResultEditVO> manageSpecValueResultEditsList = new ArrayList<>();
                for (ManageSpecValueResultVO manageSpecValueResult:specValueList){
                    ManageSpecValueResultEditVO manageSpecValueResultEdit = new ManageSpecValueResultEditVO();
                    specValueQuery.setSpecId(manageSpecValueResult.getSpecId());
                    List<ManageSpecValueResultSolVO> stringList = goodsSpecValueMapper.selectByShopId3(specValueQuery);
                    manageSpecValueResultEdit.setCatId(manageSpecValueResult.getCatId());
                    manageSpecValueResultEdit.setSpecId(manageSpecValueResult.getSpecId());
                    manageSpecValueResultEdit.setSpecName(manageSpecValueResult.getSpecName());
                    manageSpecValueResultEdit.setSpecValueId(manageSpecValueResult.getSpecValueId());
                    manageSpecValueResultEdit.setSpecValueNames(stringList);
                    manageSpecValueResultEditsList.add(manageSpecValueResultEdit);
                }

                common.setCommonSpecValueList(manageSpecValueResultEditsList);
            }
            List<ManageGdsBaseAddResultVO> gdsBases = this.baseMapper.selectGoodsSpecBygoodsIsShelves(commonId);
            ManageGdsBaseAddResultVO gdsBase = gdsBases.get(0);
            common.setSellingPoint(gdsBase.getSellingPoint());
            common.setGoodsSendBack(gdsBase.getGoodsSendBack());
            GdbMerchantGoodsCommonDetailVO goodsCommonDetail = goodsCommonDetailMapper.selectByPrimaryKey(commonId);
            List<GdbMerchantGuiGeGoodsImagesDTO> merchantGuiGeGoodsImages = new ArrayList<>();

            // 商品图片
            for (ManageGdsBaseAddResultVO base : gdsBases) {
                GdbMerchantGuiGeGoodsImagesDTO guiGeGoodsImages = new GdbMerchantGuiGeGoodsImagesDTO();
                // 商品图片
                List<GdbMerchantGoodsImagesVO> goodsImages = goodsImagesMapper.selectByCommonId3(commonId, Integer.valueOf(shopId), base.getGoodsId());

                if (CollectionUtils.isEmpty(goodsImages)) {
                    GdbMerchantGoodsImagesVO goodsImage = new GdbMerchantGoodsImagesVO();
                    goodsImage.setImagesImage(common.getCommonImage());
                    goodsImage.setImagesDisplayorder(0);
                    goodsImage.setShopId(shopId);
                    goodsImage.setImagesIsDefault(1);
                    goodsImages.add(goodsImage);
                    guiGeGoodsImages.setMerchantGoodsImages(goodsImages);
                    merchantGuiGeGoodsImages.add(guiGeGoodsImages);
                } else {
                    guiGeGoodsImages.setMerchantGoodsImages(goodsImages);
                    merchantGuiGeGoodsImages.add(guiGeGoodsImages);
                }
            }
            commonResult.setGoodsImages(merchantGuiGeGoodsImages);
            commonResult.setCommonResult(common);
            commonResult.setGdsBases(gdsBases);
            commonResult.setGoodsCommonDetail(goodsCommonDetail);

            BaseGoodsConfigVO manageGdsGoodsConfig = goodsDelayConfigMapper.selectByPrimaryKey(commonId);
            commonResult.setManageGdsGoodsConfig(manageGdsGoodsConfig);

            List<MerchantShopGoodsCatDTO> shopGoodsCatList = shopGoodsCatMapper.queryByCommonId(commonId);
            commonResult.setShopGoodsCatList(shopGoodsCatList);
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }

        return ResponseResult.success(commonResult);
    }

    @Override
    public ResponseResult isMeGoods(DealerGoodsUserInfoDTO goodsUserInfo) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(goodsUserInfo.getToken());
        String shopId = userInfo.getShopId();
        //判断是否是自己的商品
        Integer count = this.baseMapper.isMeGoods(shopId,goodsUserInfo.getCommonId());
        if(null!= count && count >= 1){
            return ResponseResult.fail(BizCodeEnume.GOODS_NOT_WORKING);
        }else{
            return ResponseResult.success();
        }
    }
    @Override
    public ResponseResult queryAllGoodsInfo(PlatFormAllGoodsDTO param) {

        try {
            ResponseResult  result = queryAllGoods(param);
//            PageUtils pageUtils= (PageUtils) result.getData();

//            @SuppressWarnings("unchecked")
//            List<PlatFormAllGoodsVO> recGoods = (List<PlatFormAllGoodsVO>) pageUtils.getList();
//            Integer totalCount = pageUtils.getTotalCount();
//            for (int x = 0; x < recGoods.size(); x++) {
//                Integer commonId = recGoods.get(x).getCommonId();
//                String goodsId =selectByCommonId(commonId);
//                recGoods.get(x).setGoodsId(goodsId);
//            }
            return result;
        } catch (Exception e) {
            LOG.error("[queryAllGoods]-platform-入参：{}-异常：{}", JsonUtils.toString(param), e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult selectCommodityDetailsExp(GoodsDetailsDTO param, HttpServletResponse response) {
        String[] title = { "goodsId", "commonId", "店铺名称", "商品名称", "商品价格", "商品库存", "商品规格" };

        List<Map<String, String>> mapList = Lists.newArrayList();

        List<GoodsDetailsDTO> list = this.baseMapper.selectCommodityDetails(param);

        for (GoodsDetailsDTO res : list) {
            HashMap<String, String> map = com.google.common.collect.Maps.newHashMap();
            // 订单状态 1.待付款 2.已付款 3.待发货 4.已发货 5.已签收 6.确认收货 7.取消 8.退款中 9.已退款 11.待自提',
            map.put("goodsId", res.getGoodsId());
            map.put("commonId", res.getCommonId());
            map.put("店铺名称", res.getShopName());
            map.put("商品名称", res.getGoodsName());
            map.put("商品价格", res.getGoodsPrice() + "");
            map.put("商品库存", res.getGoodsStock() + "");
            map.put("商品规格", res.getSpecValueName() + "");

            mapList.add(map);
        }
        // excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map = Maps
                .newHashMap();
        map.put("商品详情", mapList);
        String url = ExcelsUtil.createExcel(title, map, new int[] { 0 }/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);


        return ResponseResult.success(url);
    }

    @Override
    public ResponseResult selectCommodityDetails(GoodsDetailsDTO param) throws IllegalAccessException {
        Map data= ParseMapUtils.beanToMap(param);
        IPage<GoodsDetailsDTO> page=this.baseMapper.selectCommodityDetailsByPage(new Query<GoodsDetailsDTO>().getPage(data),
                param);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult selectGoodsDetailByRct(Map<String, Object> paraMap) {
        IPage<GoodsBaseEntity> page=this.baseMapper.selectGoodsDetailByRct(new Query<GoodsBaseEntity>().getPage(paraMap),
                paraMap);
        return ResponseResult.success(PageUtils.getPage(page));

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updateGoodsBaseByMap(Map<String, Object> map) {
        Integer count = this.baseMapper.updateGoodsBaseByMap(map);
        if (count > 0) {
            return ResponseResult.success(BizCodeEnume.UPDATE_SUCCEEDED);
        }
        return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);
    }

    @Override
    public ResponseResult updateGoodsBaseState(CommonShopStateDTO commonParam) {
        Integer count = this.baseMapper.updateGoodsBaseState(commonParam);
        if (count > 0) {
            return ResponseResult.success(BizCodeEnume.UPDATE_SUCCEEDED);
        }
        return ResponseResult.fail(BizCodeEnume.UPDATE_ERROR);
    }

    @Override
    public ResponseResult deleteIntegralGoods(ManageCommonIdsDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (null != userInfo) {
            List<Integer> commonIds = param.getCommonIds();
            goodsCommonMapper.updateCommonDel(commonIds);
            this.baseMapper.updateCommonDel(commonIds);
            goodsCommonDetailMapper.deleteByPrimaryKey(commonIds);
            goodsImagesMapper.deleteByCommonid(commonIds);
            return ResponseResult.success(BizCodeEnume.DELETE_SUCCESS);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult queryIntegralGoodsAll(Map<String, Object> param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.get("token").toString());
        if (null != userInfo) {
            //将对象转换为map
            //Map data = ParseMapUtils.beanToMap(param);
            //分页查询数据
            Page<IntegraMallGoodsVO> page = new Page<>((Integer) param.get("page"),(Integer) param.get("limit"));
            IPage<IntegraMallGoodsVO> result = this.baseMapper.queryIntegralGoodsAll(page, param);

            return ResponseResult.success(PageUtils.getPage(result));
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
    }

    @Override
    public ResponseResult getGoodsCommonDetails(Integer commonId) {
        List<ReceiveGoodsDetailsVO> detailList = this.baseMapper.selectCartMessageByCommonId(commonId);
        for(ReceiveGoodsDetailsVO detail : detailList) {
            detail.setGoodsSpecChineseValue(detail.getGoodsSpecChineseValue());

            if (!detail.getCommonState().equals(1) || !detail.getCommonVerify().equals(1)
                    || !detail.getCartStatus().equals(1)) {
                detail.setGoodsStock(0);
                detail.setCartStatus(0);
            }

            // 不限购
            if (detail.getCommonLimit().equals(0) || detail.getGoodsMaxSale().equals(0)) {
                detail.setGoodsMaxSale(detail.getGoodsStock());
            }
            // 活动
            ActivityGoodsDetailDTO activityGoodsDetail = dealActivity(detail.getGoodsId(), detail.getGoodsMaxSale(),
                    detail.getCommonId(), detail.getCommonIsXian());

            if (null != activityGoodsDetail && !activityGoodsDetail.getActivityStatus().equals(0)) {
                detail.setActivityStatus(activityGoodsDetail.getActivityStatus());
                detail.setActivityGoodsDetail(activityGoodsDetail);
                detail.setCommonIsXian(activityGoodsDetail.getActivityStatus());
                if (!activityGoodsDetail.getActivityStatus().equals(4)) {
                    detail.setGoodsMaxSale(activityGoodsDetail.getGoodsUpperLimit());
                    detail.setGoodsMinSale(activityGoodsDetail.getGoodsLowerLimit());
                }
            } else {
                detail.setActivityStatus(0);
                detail.setActivityGoodsDetail(new ActivityGoodsDetailDTO());
                detail.setCommonIsXian(0);
            }

            if (detail.getGoodsMaxSale().equals(0)) {
                detail.setGoodsMaxSale(detail.getGoodsStock());
            }

        }

        return ResponseResult.success(JsonUtils.toString(detailList));
    }

    @Override
    public ResponseResult queryByGoodsBaseList2(ManageCommonIdsDTO param) {
        List<ManageGoodsBaseListResultDTO> goodsBases = new ArrayList<ManageGoodsBaseListResultDTO>();
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.getToken());

        if (userPermissionsResult.getFlag()) {
            goodsBases = this.baseMapper.selectByGoodsList2(param.getCommonIds());
            for (ManageGoodsBaseListResultDTO goodsBase : goodsBases) {

                goodsBase.setGoodsSpec(goodsBase.getGoodsSpec());
            }
        } else {
            return  ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        return ResponseResult.success(goodsBases);
    }

    @Override
    public ResponseResult batchUpdateGoodsPrice(Map<String, Object> param) {
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                param.get("token").toString());
        if (userPermissionsResult.getFlag()) {
            //更新类型: 1-覆盖调价 2-浮动调价 3-分别调价
            Integer updateType = (Integer) param.get("updateType");
            //1-覆盖调价
            if (null != updateType && updateType == 1) {
                goodsCommonMapper.updateCommonPriceUni1(param);
                this.baseMapper.updateGoodsPriceUni1(param);
                //2-浮动调价
            } else if (null != updateType && updateType == 2) {
                List<Integer> commonIds = (List<Integer>) param.get("commonIds");
                Integer operType = Integer.parseInt((String) param.get("operType"));
                BigDecimal operValue = new BigDecimal((String) param.get("operValue"));
                for (Integer commonId : commonIds) {
                    GoodsCommonEntity goodsPriceEntity = goodsCommonMapper.selectById(commonId);
                    BigDecimal commonPrice = goodsPriceEntity.getCommonPrice();
                    BigDecimal commonMarketPrice = goodsPriceEntity.getCommonMarketPrice();
                    param.put("commonId", commonId);
                    ////1-加 2-减 3-乘
                    if (null != operType) {
                        if (1 == operType) {
                            commonPrice = commonPrice.add(operValue);
                            commonMarketPrice = commonMarketPrice.add(operValue);
                        } else if (2 == operType) {
                            commonPrice = commonPrice.subtract(operValue);
                            commonMarketPrice = commonMarketPrice.subtract(operValue);
                        } else if (3 == operType) {
                            commonPrice = commonPrice.multiply(operValue);
                            commonMarketPrice = commonMarketPrice.multiply(operValue);
                        }
                        commonPrice = commonPrice.setScale(2, RoundingMode.UP);
                        commonMarketPrice = commonMarketPrice.setScale(2, RoundingMode.UP);
                        param.put("commonPrice", commonPrice);
                        param.put("commonMarketPrice", commonMarketPrice);
                        goodsCommonMapper.updateCommonPriceSep(param);
                        this.baseMapper.updateGoodsPriceSep(param);
                    }
                }
                //3-分别调价
            } else if (null != updateType && updateType == 3) {
                List<Map<String, Object>> mapList = (List<Map<String, Object>>) param.get("commonInfos");
                for (Map<String, Object> map : mapList) {
                    goodsCommonMapper.updateCommonPriceSep2(map);
                    this.baseMapper.updateGoodsPriceSep2(map);
                }
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

        RedisUtil.remove(this.pcIndexConfig);

        return ResponseResult.success();
    }

    @Override
    public ResponseResult updateSupperGoodsPrice(UpdateSupperGoodsPriceDTO param) {
        if(null != param){
            //从供应商同步过来的商品 改价后直接审核 通过
            List<SupperGoodsPriceDTO> supperGoodsPriceList = param.getData();
            //修改goodsCommon价格
            goodsCommonMapper.updateCommonPrice(supperGoodsPriceList.get(0));
            //修改商品是否编辑过价格
            goodsCommonMapper.updateIsUpdatePrice(supperGoodsPriceList.get(0));
            for (SupperGoodsPriceDTO supperGoodsPrice : supperGoodsPriceList) {
                //修改goodsBase 价格
                this.baseMapper.updateGoodsPrice(supperGoodsPrice);
            }
            return ResponseResult.success();
        }
        return ResponseResult.fail();
    }

    @Override
    public ResponseResult querySupperGoodsPrice(Map<String, Object> param) {
        if(null != param && null != param.get("token") && null != param.get("commonId")){
            // 权限判断
            UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_GOODS,
                    param.get("token").toString());

            if (userPermissionsResult.getFlag()) {
                //根据common 查询供应商商品的商品规格价格
                List<Map<String,Object>> result =  goodsCommonMapper.querySupperGoodsPrice(param.get("commonId").toString());
                return ResponseResult.success(result);
            } else {
                return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
            }
        }
        return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER);
    }

    @Override
    public ResponseResult queryByTypeId(ManageByTypeIdParamInfoDTO param) {
        // 封装返回结果
        ManageGdsVO manageGdsAddResult = new ManageGdsVO();

        String typeId = param.getTypeId();
        String gooddId = param.getGoodsId();
        GoodsBaseEntity entity= this.baseMapper.selectById(gooddId);
        Integer shopId = entity.getShopId();
        //根据goodsid查询商品规格
        String specvalue1 =entity.getSpecValue();
        List<GoodBaseSpecValuesVO> specValuesJsonBeans = new ArrayList<>();
        JSONArray specValuesJsonBeanArray = com.alibaba.fastjson.JSONObject.parseArray(specvalue1);
        for (int index = 0; index < specValuesJsonBeanArray.size(); index++) {
            com.alibaba.fastjson.JSONObject obj = specValuesJsonBeanArray.getJSONObject(index);
            GoodBaseSpecValuesVO temp = JSONObject.parseObject(obj.toJSONString(), GoodBaseSpecValuesVO.class);
            specValuesJsonBeans.add(temp);
        }
        manageGdsAddResult.setSpecValueList(specValuesJsonBeans);
        // 根据typeId查询属性名
        List<ManagePropertyValueVO> propertyNames = goodsPropertyMapper.selectByTypeId2(Integer.valueOf(typeId));
        // 根据typeId查询规格名称和id
        List<ManageSpecNameVO> specvalue = goodsSpecMapper.selectByTypeId(Integer.valueOf(typeId));

        // 根据店铺id查询规格列表
        ManageSpecValueInfoDTO manageSpecValueQuery = new ManageSpecValueInfoDTO();
        manageSpecValueQuery.setShopId(shopId.toString());
        manageSpecValueQuery.setCatId(param.getCatId().toString());
        manageSpecValueQuery.setTypeId(Integer.valueOf(param.getTypeId()));

        StringBuilder specIdVar = new StringBuilder();
        List<String> specIdStringList = new ArrayList<>();
        for (ManageSpecNameVO specValueQuery : specvalue) {
            specIdStringList.add(specValueQuery.getSpecId().toString());

        }
        StringBuilder sb = new StringBuilder();
        for (String s : specIdStringList) {
            //该步即不会第一位有逗号，也防止最后一位拼接逗号！
            if (sb.length() > 0) {
                sb.append(",");
            }
            sb.append(s);
        }
        manageSpecValueQuery.setSpecId(sb.toString().trim());
        System.out.println(manageSpecValueQuery.getSpecId());
        List<ManageSpecValueVO> manageSpecValueResultParams = new ArrayList<>();
        manageSpecValueResultParams = goodsSpecValueMapper.selectByResultParam(manageSpecValueQuery);
        if (manageSpecValueResultParams == null || manageSpecValueResultParams.isEmpty()) {
            manageSpecValueResultParams = goodsSpecValueMapper.selectByResultParam2(manageSpecValueQuery);
        }
        List<String> list = new ArrayList<>();
        if (null != param.getGoodsId()) {

            String var1 = entity.getGoodsSpec();
            String[] split = var1.split("\\+");
            list.addAll(Arrays.asList(split));

        }

        Map<String, List<Map<String, Object>>> specNameMap = new HashMap<>();
        // 过滤相同得规格
        for (ManageSpecValueVO record : manageSpecValueResultParams) {
            specNameMap.put(record.getSpecName(), null);
        }
        List<Map<String, Object>> listMap;
        for (ManageSpecValueVO record : manageSpecValueResultParams) {
            listMap = specNameMap.get(record.getSpecName());
            if (null == listMap) {
                listMap = new ArrayList<>();
            }
            Map<String, Object> specNameM = new HashMap<>();
            specNameM.put("goodsId", record.getGoodsId());
            System.out.println(record.getSpecValueName());
            specNameM.put("specValueName", record.getSpecValueName());
            specNameM.put("commonId", entity.getCommonId());
            specNameM.put("marking", "false");
            for (String flags : list) {
                if (flags.equals(record.getSpecValueName())) {
                    specNameM.put("marking", "true");
                }
            }


            listMap.add(specNameM);
            specNameMap.put(record.getSpecName(), listMap);
        }

        List<ManageGoodsSpecValueVO> specValueNameList = new ArrayList<>();
        if (!specvalue.isEmpty()) {
            for (ManageSpecNameVO specValueResult : specvalue) {

                specValueResult.setSpecValueNames(specNameMap.get(specValueResult.getSpecName()));
            }
        }
        // 获取售卖区域
        // List<TransportAreaResult> transportArea =
        // this.getTransportArea(shopId);
        // 获取运费模板
        List<TransportTemplateVO> transportTemplate = businessServiceClient.selectByShopId(shopId);
        // 查询店铺自定义商品分类
        List<ManageShopSelfCatMenuVO> shopSelfCatMenu = this.getShopSelfCatMenu(shopId);
        // 查询关联板式
        List<ManageGoodsFormatVO> goodsFormats = this.baseMapper.selectByShopId(shopId);


        manageGdsAddResult.setPropertyNames(propertyNames);
        manageGdsAddResult.setSpecValueName(specvalue);
        manageGdsAddResult.setSpecValues(specValueNameList);

        manageGdsAddResult.setTransportTemplate(transportTemplate);
        manageGdsAddResult.setShopSelfCatMenu(shopSelfCatMenu);
        manageGdsAddResult.setGoodsFormats(goodsFormats);

        return ResponseResult.success(manageGdsAddResult);
    }

    @Override
    public ResponseResult insertOssPhotoPort(OssPhotoInsertDTO param) {
        String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + param.getToken());
        Map<String, Object> map = new HashMap<String, Object>();
        UserInfoVO userInfo = JsonUtils.toBean(userInfoStr, UserInfoVO.class);
        String photoUrl=null;
        if (userInfoStr != "" && userInfoStr != null) {

            int i = 0;
            for (photoUrlDTO par : param.getOssparam()) {
                // 解密

                if (i != 0) {
                    photoUrl += "," + par.getPhotoUrl();
                } else {
                    photoUrl = par.getPhotoUrl();

                }
                i++;
            }

            GoodsBaseEntity goods = this.baseMapper.selectById(param.getGoodsId());
            map.put("userId", userInfo.getUserId());
            map.put("userName", userInfo.getUserName());
            map.put("goodsId", param.getGoodsId());
            map.put("shopId", goods.getShopId());
            map.put("shopName", goods.getGoodsName());
            map.put("image", goods.getGoodsImage());
            map.put("goodsName", goods.getGoodsName());
            map.put("reportImage", photoUrl);
            map.put("typeId", param.getTypeId());
            map.put("typeName", param.getTypeName());
            map.put("reportContent", param.getReportContent());
            this.baseMapper.insertReport(map);
        } else {

            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryGdsDetail(WapGoodsDetailQueryDTO param) {
        try{
            GdsDetailPageResultVO detailPage = new GdsDetailPageResultVO();
            // 获取user信息
            UserInfoVO userinfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(param.getToken());
            // 查询商品详情
            GdsBaseDetailResultVO goodsBases = this.baseMapper.selectByGoodsId(param.getGoodsId());
            if (null == goodsBases) {
                return ResponseResult.fail(0, "商品下架或不存在");
            }
            if (goodsBases != null && goodsBases.getGoodsType() == 2){
                return  ResponseResult.fail(0, "温馨提示：供应商商品仅支持在电脑端查看~");
            }
            if (!goodsBases.getGoodsIsShelves().equals(1) || !goodsBases.getCommonState().equals(1)
                    || !goodsBases.getCommonVerify().equals(1)) {
                goodsBases.setGoodsStock(0);
            }
            if (StringUtils.isNotEmpty(goodsBases.getSpecValue())) {
                List<GoodBaseSpecValuesJsonBeanVO> specValuesJsonBeans = new ArrayList<>();
                JSONArray specValuesJsonBeanArray = JSONObject.parseArray(goodsBases.getSpecValue());
                for(int index = 0;index < specValuesJsonBeanArray.size();index++) {
                    JSONObject obj = specValuesJsonBeanArray.getJSONObject(index);
                    GoodBaseSpecValuesJsonBeanVO temp = JSONObject.parseObject(obj.toJSONString(), GoodBaseSpecValuesJsonBeanVO.class);
                    specValuesJsonBeans.add(temp);
                }
                goodsBases.setSpecValueList(specValuesJsonBeans);
            }

            Integer commonId = goodsBases.getCommonId();

            Integer catId = null;

            if (null != goodsBases) {
                goodsBases.setGoodsSpec(goodsBases.getGoodsSpec());
                // 爆品价格
                HotGoodsDTO hotGoodsDTO = goodsHotMapper.selectByPrimaryKey(goodsBases.getGoodsId());
                if(null != hotGoodsDTO && hotGoodsDTO.getGoodsState().intValue() == 2){
                    goodsBases.setGoodsPrice(hotGoodsDTO.getGoodsPrice());
                }

                Integer shopId = goodsBases.getShopId();
                GdsShopDetailResultVO shopDetail =null;
                if(0 != shopId){
                    shopDetail = this.baseMapper.selectShopDetailByShopId(shopId);
                    if (shopDetail == null) {
                        return ResponseResult.fail(0, "店铺信息为null", null);
                    }
                    // 获取店铺评分
                    getShopScore(shopId, shopDetail);
                    // 设置店铺默认值
                    setShopDefaultValue(goodsBases, shopDetail);
                    Integer result = 0;
                    Map<Object, Object> paramTmp = new HashMap<>();
                    paramTmp.put("shopId",shopId);
                    InvoiceSwitchEntityVO data = this.baseMapper.queryInvoiceSwitch(paramTmp);
                    Integer invoiceSwitchStatus = data.getInvoiceSwitchStatus();
                    Integer invoiceAuditStatus = data.getInvoiceAuditStatus();
                    if(1 == invoiceAuditStatus && 1 == invoiceSwitchStatus){
                        result = 1;
                    }else if(2 == invoiceAuditStatus && 0 == invoiceSwitchStatus){
                        result = 1;
                    }
                    shopDetail.setInvoiceActive(result);
                }else{
                    shopDetail = new GdsShopDetailResultVO();
                    shopDetail.setShopId(0);
                    shopDetail.setShopName("平台店铺");
                    shopDetail.setShopLogo("");
                    shopDetail.setShopCount(0);
                    shopDetail.setShopCollect(0);
                    shopDetail.setWapShopLogo("");
                    shopDetail.setInvoiceActive(0);
                }



                // 查询公共信息
                GdsCommonResultVO gdsCommon = goodsCommonMapper.selectTransport(commonId);
                if (StringUtils.isNotEmpty(gdsCommon.getSpecParam())) {
                    List<SpecParamJsonBeanVO> list = new ArrayList<>();
                    JSONArray jsonSpecParam = JSONObject.parseArray(gdsCommon.getSpecParam());
                    for(int index = 0;index < jsonSpecParam.size();index++) {
                        JSONObject obj = jsonSpecParam.getJSONObject(index);
                        SpecParamJsonBeanVO temp = JSONObject.parseObject(obj.toJSONString(), SpecParamJsonBeanVO.class);
                        list.add(temp);
                    }
                    gdsCommon.setSpecParamList(list);
                }
                // 不限购
                if (gdsCommon.getCommonLimit().equals(0) || goodsBases.getGoodsMaxSale().equals(0)) {
                    goodsBases.setGoodsMaxSale(goodsBases.getGoodsStock());
                }

                // 活动
                ActivityGoodsDetailDTO activityGoodsDetail = goodsCommonService.dealActivity2(goodsBases.getGoodsId(),goodsBases.getGoodsStock(),
                        goodsBases.getGoodsMaxSale(), commonId, gdsCommon.getCommonIsXian(),userinfo.getUserId(),param.getSessionTime());

                if (null != activityGoodsDetail && !activityGoodsDetail.getActivityStatus().equals(0)) {
                    goodsBases.setActivityStatus(activityGoodsDetail.getActivityStatus());
                    goodsBases.setActivityGoodsDetail(activityGoodsDetail);
                    if (!activityGoodsDetail.getActivityStatus().equals(4)) {
                        goodsBases.setGoodsMaxSale(activityGoodsDetail.getGoodsUpperLimit());
                        goodsBases.setGoodsMinSale(activityGoodsDetail.getGoodsLowerLimit());
                    }
                    //满减赠折活动展示活动内容ZZZ
                    if (activityGoodsDetail.getActivityStatus().equals(5)) {
                        String promotionContent = "";
                        List<ManjianzengzhePromotionContentQueryResultVO> promotionContents =
                                this.baseMapper.selectManjianzengzhePromotionContent(commonId);
                        for (ManjianzengzhePromotionContentQueryResultVO r : promotionContents) {
                            Integer discountType = r.getDiscountType();
                            Integer hasGiveaway = r.getHasGiveaway();
                            String discountContent = r.getDiscountContent();
                            boolean mzFlag = discountContent == null || "".equals(discountContent);
                            //满减赠
                            if (discountType == 1) {
                                if(null == goodsBases.getPromotionType() || "".equals(goodsBases.getPromotionType()) ) {
                                    if(hasGiveaway == 1 && mzFlag){
                                        goodsBases.setPromotionType("满赠");
                                    }else{
                                        goodsBases.setPromotionType("满减");
                                    }
                                }
                                //满折
                            } else if (discountType == 3) {
                                goodsBases.setPromotionType("满折扣");
                            }
                            if ("满减".equals(goodsBases.getPromotionType()) && hasGiveaway == 1) {
                                goodsBases.setPromotionType("满减赠");
                            }else if("满赠".equals(goodsBases.getPromotionType())&&!mzFlag){
                                goodsBases.setPromotionType("满减赠");
                            }
                            goodsCommonService.dealPromotionContent(r);

                            promotionContent = promotionContent + r.getPromotionContent() + "\n";

                        }
                        goodsBases.setPromotionContent(promotionContent);



                    }
                    activityGoodsDetail.setGoodsPrice(goodsBases.getGoodsPrice());
                    gdsCommon.setCommonIsXian(activityGoodsDetail.getActivityStatus());
                } else {
                    goodsBases.setActivityStatus(0);
                    goodsBases.setActivityGoodsDetail(new ActivityGoodsDetailDTO());
                    gdsCommon.setCommonIsXian(0);
                }

                catId = gdsCommon.getCatId();

                // 设置规格名称和规格值
                setCommonSpec(gdsCommon);

                // 查询图片信息
                List<GdsImageDetailResultVO> goodsImages = goodsImagesMapper.selectByCommonId(param.getGoodsId().toString(),shopId);
                if (CollectionUtils.isEmpty(goodsImages)) {
                    GdsImageDetailResultVO goodsImage = new GdsImageDetailResultVO();
                    goodsImage.setImagesImage(gdsCommon.getCommonImage());
                    goodsImage.setImagesDisplayorder(0);
                    goodsImage.setImagesIsDefault(1);


                    goodsImages.add(goodsImage);
                }

                // 处理结果。防止出现null或空，影响ios
                GdsShopDetailResultVO detailResultVO = new GdsShopDetailResultVO();
                detailResultVO.setShopId(0);
                detailResultVO.setShopName("");
                detailResultVO.setShopLogo("");
                detailResultVO.setShopCount(0);
                detailResultVO.setShopCollect(0);
                detailResultVO.setWapShopLogo("");

                detailPage.setGoodsBases(goodsBases);
                detailPage.setGoodsImages(goodsImages != null ? goodsImages : new ArrayList<GdsImageDetailResultVO>());
                detailPage.setShopDetail(shopDetail != null ? shopDetail : detailResultVO);
                detailPage.setGdsCommon(gdsCommon);

                // 分销商品信息
                FxGoodsListDTO goodsListRequest = new FxGoodsListDTO(goodsBases.getGoodsId());
                List<FXGoodsListVO> fxGoodsList =  this.baseMapper.queryFxGoodsList(goodsListRequest);
                if(!CollectionUtils.isEmpty(fxGoodsList) && fxGoodsList.size() == 1){
                    detailPage.setFxGoodsList(fxGoodsList.get(0));
                }
            }

            // 更新点击量
            this.baseMapper.updateGoodsClick(param.getGoodsId().toString());
            goodsCommonMapper.updateGoodsClick(commonId);
            // 添加足迹
            String token = param.getToken();
            if (token != null && !token.equals("")) {
                goodsCommonService.addUserFoot(userinfo, commonId, catId);
            }

            return ResponseResult.success(detailPage);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult queryFootPrintH5(GuessYouLikeQueryDTO param) {
        Map result = new HashMap();
        List<WapCommonBaseUserFootVO> commonBases = Lists.newArrayList();
        Integer totalCount = 0;
        String token = param.getToken();

        if (StringUtils.isNotBlank(token) && RedisUtil.exists(token)) {
            //获取用户信息
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
            // 查询店铺自定义商品分类
            List<Integer> catIds = this.baseMapper.selectCartGuessLikeGoods2(userInfo.getUserId());
            param.setCatIds(catIds);
        }
        commonBases = this.baseMapper.selectAppGuessLikeH5(param);
        result.put("count", commonBases.size());
        if (param.getLimit() * param.getPage() < commonBases.size()) {
            totalCount = param.getLimit() * param.getPage();
        } else {
            totalCount = commonBases.size();
        }

        commonBases = commonBases.subList((param.getPage() - 1) * param.getLimit(), totalCount);

        for (WapCommonBaseUserFootVO gdsListQueryResult : commonBases) {

            gdsListQueryResult.setGoodsIdOne(Integer.parseInt(gdsListQueryResult.getGoodsId()));
            if (gdsListQueryResult.getGoodsIdOne().equals(1)) {
                List<Integer> goodsIds = this.baseMapper.selectGoodsId(gdsListQueryResult.getCommonId());
                if (!CollectionUtils.isEmpty(goodsIds)) {
                    gdsListQueryResult.setGoodsIdOne(goodsIds.get(0));
                }
            }

            Integer commonIsXian = gdsListQueryResult.getCommonIsXian();

            // 活动
            ActivityGoodsDetailDTO activityGoodsDetail = dealActivity(gdsListQueryResult.getGoodsIdOne(), null,
                    gdsListQueryResult.getCommonId(), commonIsXian);

            if (null != activityGoodsDetail && activityGoodsDetail.getActivityStatus() != 0) {
                gdsListQueryResult.setActivityStatus(activityGoodsDetail.getActivityStatus());
                gdsListQueryResult.setActivityGoodsDetail(activityGoodsDetail);
                gdsListQueryResult.setCommonIsXian(activityGoodsDetail.getActivityStatus());
                gdsListQueryResult.setCommonPrice(activityGoodsDetail.getActivityPrice());
                if (activityGoodsDetail.getActivityStatus() == 5) {
                    gdsListQueryResult.setCommonPrice(activityGoodsDetail.getMjzzPrice());
                }
            } else {
                gdsListQueryResult.setActivityStatus(0);
                gdsListQueryResult.setActivityGoodsDetail(new ActivityGoodsDetailDTO());
                gdsListQueryResult.setCommonIsXian(0);
            }
        }
        result.put("commonBases", commonBases);
        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult getGoodsPoster(Map<String, Object> param) {
        Map<String, Object> map = new HashMap<>();
        String orCode = null;// 二维码的base64位
        try {
            AccessTokenUtil.queryAccessToken();
            String token = (String) param.get("token");
            // 1 是 h5  2 是小程序
            String type = (String) param.get("type");
            //商品id
            String goodsId = (String) param.get("goodsId");

            //获取用户信息
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
            // 封装用户名
            map.put("userName", userInfo.getUserName());
            // 封装用户id
            map.put("userId", userInfo.getUserId());
            //封装用户头像
            map.put("userAvatar", userInfo.getUserAvatar());
            // 获取海报的背景图
            NavSortLogoDTO gdbNavSortLogoDTO = new NavSortLogoDTO();
            gdbNavSortLogoDTO.setConfigKey("h5_goods_image");
            ResponseResult resp1 = baseServiceClient.quertNavLogo(gdbNavSortLogoDTO);
            List<Map<String, Object>> list = (List<Map<String, Object>>) resp1.getData();
            DecimalFormat df = new DecimalFormat("#.00");
            if (null != list && list.size() > 0) {
                //海报背景图
                String posterImageUrl = list.get(0).get("configValue").toString();
                map.put("posterImageUrl", posterImageUrl);
                //获取商品信息
                GoodsPosterVO gdsListQueryEsResult = this.baseMapper.getGoodsPoster(Integer.valueOf(goodsId));
                map.put("goodsId",gdsListQueryEsResult.getGoodsId());
                map.put("commonId",gdsListQueryEsResult.getCommonId());
                map.put("commonName",gdsListQueryEsResult.getCommonName());
                map.put("commonImage",gdsListQueryEsResult.getCommonImage());
                if(null != gdsListQueryEsResult.getCommonIsXian() && !gdsListQueryEsResult.getCommonIsXian().equals(0)){
                    BigDecimal goodsPrice = new BigDecimal(0);
                    if (gdsListQueryEsResult.getCommonIsXian().equals(2)) {
                        // 秒杀
                        AppSeckillGoodsQueryResultVO seckillGoods = activityServiceClient.selectSeckillByGoodsId2(Integer.valueOf(gdsListQueryEsResult.getGoodsId()));
                        goodsPrice = seckillGoods.getSeckillPrice();
                    } else if (gdsListQueryEsResult.getCommonIsXian().equals(3)) {
                        // 限时折扣
                        AppDiscountGoodsQueryResultVO discountGoods = activityServiceClient.selectDiscountByGoodsId(Integer.valueOf(gdsListQueryEsResult.getGoodsId()));
                        goodsPrice = discountGoods.getDiscountPrice();
                    } else if (gdsListQueryEsResult.getCommonIsXian().equals(4)) {
                        // 拼团
                        AppPintuanGoodsQueryResultVO pintuanGoods = activityServiceClient.selectpiecingTogetherByGoodsId(gdsListQueryEsResult.getCommonId(), Integer.valueOf(gdsListQueryEsResult.getGoodsId()));
                        goodsPrice = pintuanGoods.getPrice();
                    }else if (gdsListQueryEsResult.getCommonIsXian().equals(5)) {
                        //满减赠折 不涉及价格修改
                        goodsPrice = gdsListQueryEsResult.getCommonPrice();
                    }
                    map.put("commonPrice",goodsPrice);
                }else{
                    map.put("commonPrice",gdsListQueryEsResult.getCommonPrice());
                }
                //判断当前用户是否是微客
                Integer vkstart =  goodsCommonMapper.queryUserVkStart(userInfo.getUserId());
                //判断当前商品是否是 分销商品
                Integer vkGoodsStart =  goodsCommonMapper.queryvkGoodsStart(gdsListQueryEsResult.getGoodsId());

                if ("1".equals(type)) { // 1 是 h5  2 是小程序
                    String url = domainName + "/h5/#/pages/description/descrption?goodsId=" + gdsListQueryEsResult.getGoodsId()+"&commonId="+gdsListQueryEsResult.getCommonId();
                    if(vkstart != 0 && vkGoodsStart != 0){
                        url = url + "&shareUserId" + userInfo.getUserId() +  "&shareType = 1"+ "&isShare=true";
                    }
                    byte[] b = QrCodeUtil.createQRCode(150, 150, url);
                    // 转base 64
                    orCode = QrCodeUtil.BASE_PREFIX + Base64Utils.encode2(b);

                } else {
                    //因为生成小程序的二维码参数不能过长，所以将部分请求参数存入redis
                    StringBuilder str = new StringBuilder();//定义变长字符串
                    Random random = new Random();
                    //随机生成数字，并添加到字符串  小程序二维码不能超过 32 位
                    for (int i = 0; i < 8; i++) {
                        str.append(random.nextInt(6));
                    }
                    int num = Integer.parseInt(str.toString());
                    //生成markid key
                    System.out.println("codeId=" + num + "&codeType=PUTONG");
                    String fileName = AccessTokenUtil.getminiqrQr("codeId=" + num + "&codeType=PUTONG", "pages/description/descrption");
                    orCode = QrCodeUtil.BASE_PREFIX + fileName;
                    Map<String, Object> orMap = new HashMap<>();
                    orMap.put("goodsId", gdsListQueryEsResult.getGoodsId());
                    orMap.put("commonId", gdsListQueryEsResult.getCommonId());
                    if(vkstart != 0 && vkGoodsStart != 0){
                        orMap.put("shareUserId",userInfo.getUserId());
                        orMap.put("shareType",1);
                        orMap.put("isShare",true);
                    }
                    RedisUtil.set("PUTONG_" + num,JsonUtils.toString(orMap),60*60*24*30);//将拼团团id存入redis从另外接口查询
                }
                map.put("orcode", orCode);

                return ResponseResult.success(map);
            } else {
                return ResponseResult.fail(1, "获取背景图失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail(e.getMessage());

        }
    }

    @Override
    public ResponseResult queryNoneGoods(NoneGoodsQueryDTO param) throws IllegalAccessException {
        // 权限判断
//        UserPermissionsResult userPermissionsResult = UserService
//                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if (userInfoVO != null) {
            Map data = ParseMapUtils.beanToMap(param);
            IPage<GoodsRecResultDetailVO> page = this.baseMapper.selectNoneGoods(new Query<GoodsRecResultDetailVO>().getPage(data),
                    param);
            if (!CollectionUtils.isEmpty(page.getRecords())) {
                for (GoodsRecResultDetailVO good : page.getRecords()) {
                    Integer commonIsXian = good.getCommonIsXian();
                    // 活动
                    ActivityGoodsDetailDTO activityGoodsDetail = dealActivity(
                            Integer.parseInt(good.getGoodsId()), null,good.getCommonId(),
                            commonIsXian);

                    if (null != activityGoodsDetail && activityGoodsDetail.getActivityStatus() != 0) {
                        good.setActivityStatus(activityGoodsDetail.getActivityStatus());
                        good.setActivityGoodsDetail(activityGoodsDetail);
                        good.setCommonIsXian(activityGoodsDetail.getActivityStatus());
                        good.setCommonPrice(activityGoodsDetail.getActivityPrice());
                        if(activityGoodsDetail.getActivityStatus() == 5){
                            good.setCommonPrice(activityGoodsDetail.getMjzzPrice());
                        }
                    } else {
                        good.setActivityStatus(0);
                        good.setActivityGoodsDetail(new ActivityGoodsDetailDTO());
                        good.setCommonIsXian(0);
                    }

                }
            }
            return ResponseResult.success(PageUtils.getPage(page));
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
    }

    @Override
    public ResponseResult uploadToOss(OssUploadUpdateParamDTO param) {
        param.setFileUrl("file/upload/shop/settled/");
        //获取OSS配置文件中的阿里云API的外网域名
        ResponseResult resultResp=baseServiceClient.selectOSSInfo();
        if(Arrays.asList(suffix).contains(param.getStreamName())){
            return thirdPartyServiceClient.uploadToOssBase64(param);
        }else{
            return ResponseResult.fail(0,"不支持当前格式文件");
        }
    }


    private void setCommonSpec(GdsCommonResultVO gdsCommon) {
        // 设置规格名称和规格值
//		String commonSpecName = goodsSpecMapper.selectBySpecId(Integer.parseInt(gdsCommon.getCommonSpecName()));
//		gdsCommon.setCommonSpecName(commonSpecName);
        List<CommonSpecValueVO> specValueList = JsonUtils.string2Obj(gdsCommon.getCommonSpecValue(), List.class,
                CommonSpecValueVO.class);
        List<WapCommonSpecValueVO> commonSpecValueList = Lists.newArrayList();
        if(!CollectionUtils.isEmpty(specValueList)) {
            for (CommonSpecValueVO commonSpecValue : specValueList) {
                WapCommonSpecValueVO specValue = new WapCommonSpecValueVO();
                specValue.setCommonId(commonSpecValue.getCommonId());
                specValue.setGoodsId(commonSpecValue.getGoodsId());
                String specValueName = goodsSpecValueMapper.selectById(commonSpecValue.getGoodsSpecId()) == null ? null : goodsSpecValueMapper.selectById(commonSpecValue.getGoodsSpecId()).getSpecValueName();
                specValue.setGoodsSpec(specValueName);
                commonSpecValueList.add(specValue);
            }
        }
        gdsCommon.setCommonSpecValue(null);
        gdsCommon.setCommonSpecValueList(commonSpecValueList);
    }

    private void setShopDefaultValue(GdsBaseDetailResultVO goodsBases, GdsShopDetailResultVO shopDetail) {
        if (shopDetail.getShopLogo() == null || shopDetail.getWapShopLogo() == null) {
            String configValue = baseServiceClient.selectConfigValueFeign("logo_copywriting_ico_shop");


            if (shopDetail.getShopLogo() == null) {
                shopDetail.setShopLogo(configValue);
            }
            if (shopDetail.getWapShopLogo() == null && shopDetail.getShopLogo() != null) {
                shopDetail.setWapShopLogo(configValue);
            } else {
                shopDetail.setWapShopLogo(configValue);
            }
        }

        // 查询商品数量
        Integer shopCount = goodsCommonMapper.selectByShopId(goodsBases.getShopId());
        shopDetail.setShopCount(shopCount);
        // 设置店铺默认值
        setShopDefaulValue(shopDetail);
    }
    private void setShopDefaulValue(GdsShopDetailResultVO shopDetail) {
        if (shopDetail.getShopLogo() == null || shopDetail.getWapShopLogo() == null) {
            String configValue = baseServiceClient.selectConfigValueFeign("logo_copywriting_ico_shop");
            if (shopDetail.getShopLogo() == null) {
                shopDetail.setShopLogo(configValue);
            }
            if (shopDetail.getWapShopLogo() == null) {
                shopDetail.setWapShopLogo(configValue);
            }
        }
    }

    private void getShopScore(Integer shopId, GdsShopDetailResultVO shopDetail) {

        try {
            Map<Object, Object> map=new HashMap<>();
            map.put("shopId",shopId);
            ResponseResult shopScore = businessServiceClient.shopScore(map);
            if (null != shopScore) {
                // 综合评分
                String dataString = (String) shopScore.getData();

                ShopEvaluationDTO data = JsonUtils.string2Obj(dataString, ShopEvaluationDTO.class);
                Double overallScore = null;
                if (null != data) {
                    BigDecimal setScale = new BigDecimal(data.getEvaluationDeliverycredit())
                            .add(new BigDecimal(data.getEvaluationDesccredit()))
                            .add(new BigDecimal(data.getEvaluationServicecredit()))
                            .divide(new BigDecimal(3), 1, BigDecimal.ROUND_DOWN);
                    overallScore = setScale.doubleValue();
                } else {
                    overallScore = 4.5d;
                }
                shopDetail.setOverallScore(overallScore);
            }
        } catch (Exception e) {
            LOG.info("获取店铺评分失败：{}", e.getMessage());
        }
    }


    /**
     * 查询店铺自定义商品分类
     *
     * @param shopId
     * @return
     */
    private List<ManageShopSelfCatMenuVO> getShopSelfCatMenu(Integer shopId) {
        // 获取所有的分类
        List<ManageShopSelfCatMenuVO> rootMenus = this.baseMapper.selectCustomCatByShopId(shopId);
        // 获取多级分类
        List<ManageShopSelfCatMenuVO> menuList = MenuUtils.getMenuList(rootMenus);
        return menuList;
    }




    public String selectByCommonId(Integer commonId) {
        List<Integer> list = this.baseMapper.selectList(new LambdaQueryWrapper<GoodsBaseEntity>()
                            .eq(GoodsBaseEntity::getCommonId,commonId))
                            .stream().map(GoodsBaseEntity::getGoodsId).collect(Collectors.toList());
        StringBuilder sb = new StringBuilder();
        for (int x = 0; x < list.size(); x++) {

            if (x == list.size() - 1) {

                sb.append(list.get(x));
            } else {

                sb.append(list.get(x) + ",");
            }
        }
        String string = sb.toString();
        return string;
    }

    /**
     * 查询所有商品信息
     * @param param
     * @return
     */

    public ResponseResult queryAllGoods(PlatFormAllGoodsDTO param) throws IllegalAccessException {

        Map data= ParseMapUtils.beanToMap(param);
        //查询所有商品
        IPage<PlatFormAllGoodsVO> page=this.baseMapper.selectByAllGoods(new Query<PlatFormAllGoodsVO>().getPage(data),
                param);

        for (PlatFormAllGoodsVO good : page.getRecords()) {
            if(good.getShopSelfSupport().equals("true")){
                good.setShopBusiness(2);
            } else {
                List<Integer> list = Arrays.asList(0,1,2);
                if(list.contains(good.getShopBusiness())){
                    good.setShopBusiness(1);
                }
            }
            //查询当前商品所上上架的专区
            List<String> noneNameList = goodsCommonMapper.selectNoneName(good.getCommonId());
            good.setNoneNameList(noneNameList);

            List<GoodsStockVO> stockEntityList = new ArrayList<>();
            //查询当前商品不同规格下的库存
            stockEntityList = this.baseMapper.selectStocks(good.getCommonId());
            good.setGoodsStockEntityList(stockEntityList);

            List<HotGoodsDTO> hotGoodsDTOList = getGoodsHotMapper.queryHotGoods(good.getCommonId());
            for(HotGoodsDTO hotGoodsDTO : hotGoodsDTOList){
                if(hotGoodsDTO.getGoodsState() == 1){
                    good.setHotState(1);
                    break;
                }else{
                    good.setHotState(2);
                }
            }
        }


        return ResponseResult.success(PageUtils.getPage(page));
    }
    @Override
    public ResponseResult updateSupperGoodsStart(Map<String, Object> param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.get("token").toString());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
        List<Integer> commonIds = (List<Integer>) param.get("commonIds");
        if(null != commonIds && commonIds.size() > 0){
            for (Integer commonId : commonIds) {
                // 查询代发商品 所同步的供应商商品是否在售
                Integer supplierGoodsStart = goodsCommonMapper.querySupplierGoodsStart(commonId);
                if(0 < supplierGoodsStart){
                    // 商品 不在售 所有经销商品不能 上架
                    return ResponseResult.fail(2,"有商品在供应商端未在售，商品不能上架!");
                }
            }
        }

        goodsCommonMapper.updateSupperGoodsStart(commonIds);
        Map<String,Object> map= new HashMap<>();
        map.put("commonIdS",commonIds);
        // 1 是添加  2是删除
        map.put("type",1);
        MqSendUtils.mqSendGoods(map);
        return ResponseResult.success();
    }
}

